Gotcha C# operator

August 25, 2007 on 3:13 pm | In Uncategorized | No Comments

Sometimes I have a positive feeling of “what’ta f…” reading someone else code (at a contrary to negative feeling of the same sort wchich I get way to often). Recenty I’ve found the ?? operator in C#. And really I didnt know it could by used it this way:

            string s = null;
            string s2 = s ?? "remembered";
            string s3 = s2 ?? "vorgotten";

The ?? operator returns the left operand if it not equalls null and the right one when it is. Simple and usefull!

Currency dispaly tip

August 10, 2007 on 1:09 pm | In Uncategorized | No Comments

Task: print a price according to a culture information but remember “we don’t need the damn ? (or $) sign”!

Well:

        public static string FormatCurrency(double price)
        {
            CultureInfo ci = new CultureInfo("de-DE");
            NumberFormatInfo nfi = ci.NumberFormat;
            nfi.CurrencySymbol = "";
            string s = price.ToString("c", nfi).Trim();
            return s;
        }

        public static double FromCurrency(string price)
        {
            CultureInfo ci = new CultureInfo("de-DE");
            NumberFormatInfo nfi = ci.NumberFormat;
            nfi.CurrencySymbol = "";
            double d;
            double.TryParse(price, NumberStyles.Currency, nfi, out d);
            return d;
        }

An please print the percentage but without the damn % and ALWAYS with 5 decimal digits.

        public static string FormatInterest(double interest)
        {
            CultureInfo ci = new CultureInfo("de-DE");
            NumberFormatInfo nfi = ci.NumberFormat;
            nfi.NumberDecimalDigits = 5;
            string s = interest.ToString("n", nfi).Trim();
            return s;
        }

        public static double FromInterest(string interest)
        {
            CultureInfo ci = new CultureInfo("de-DE");
            NumberFormatInfo nfi = ci.NumberFormat;
            double d;
            double.TryParse(interest, NumberStyles.Number, nfi, out d);
            return d;
        }

PS. Prase the Windows Live Writer and VSPaste plugin (it lets you paste the Visual Studio code snippets with proper text highlighting).

Powered by WordPress with Pool theme design by Borja Fernandez.
Text © Marcin Kawalerowicz. Hosting CODEFUSION.