Formatting/parsing for a specific culture

Sometimes you may want to use a specific format for formatting and parsing of textual data.  The easiest way to do this is to select a specific culture and use that with formatting and parsing methods.  Unfortunately, the CultureInfo constructor that just takes the name of the culture defaults to accepting any overrides the current user has set in Regional and Language Options.

For example, if in Regional and Language Options you have English (United States) selected and you’ve changed the currency symbol to be something other than the dollar sign ($), the following won’t use the dollar sign:

            Decimal d = 2123.5M;
            String text = String.Format(new System.Globalization.CultureInfo(“en-us”), “{0:c}”, d);

If you want to use a specific culture, you must use the CultureInfo constructor overload that accepts a Boolean so you can tell it not to use the user overrides.  For example, the following will result in a dollar sign, despite what the user has done in Regional and Language Options:

            Decimal d = 2123.5M;
            String text = String.Format(new System.Globalization.CultureInfo(“en-us”, false), “{0:c}”, d);

 

Bridges and Factories

In my previous post, I talked about Dependency Injection (DI).  One implementation of DI is using interface-oriented design to abstract a class from an injected dependency via an interface.  This is one possible implementation of the Bridge pattern.  Depending only upon an interface and classes to implement that interface opens up some very interesting possibilities.

The tried-and-true means of creating an object is to simply directly use it’s constructor, for example:

        IPerson person = new Employee(“Peter”, “Ritchie”);

This is nice and simple; but we’re still coupled to Employee despite using an IPerson object thereafter.  The above code hasn’t truly eliminated the dependency upon the Employee class. Moving all that type of logic to a single method encapsulates the logic into one, reusable, place.  This is the Factory pattern, for example:

        person = Person.Create(“Peter”, “Ritchie”);

The Create method, a “Factory Method” on a concrete (likely static) class Person, would know how to create an IPerson object.  At this point using a IPerson object is completely abstracted from a specific concrete type and its creation.

        InviteToMeeting(person);

InviteToMeeting is completely independent of the concrete type implementing IPerson (and it can actually be a private type) and how it was created or where it came from.  This abstraction leaves IPerson objects free to be created however they need to be.  The benefits of Dependency Injection, Bridge, and Factory patterns are synergistic–together they offer more than if they were apart.  In the above example they’re created as Employee objects; but because their creation is completely encapsulated it could also be affected by policy.  Policy that clients of the factory would have no dependency upon.

In the simplest case Person.Create could always just create Employee objects; but because creation is hidden from the client the factory method could use other logic to decide what classes to use.  Person.Create could be implemented this way:

    public static IPerson Create ( String firstName, String lastName )
    {
        if (Configuration.IsAdministrator)
        {
            return new Employee(firstName, lastName);
        }
        else
        {
            return new Subordinate(firstName, lastName);
        }
    }

Now we’re injecting policy into the creation process.  Somewhere, likely not in source code, whether the current user is running as an administrator.  This state is used in a policy to decide what type of IPerson object to create.


 


 

BigInteger is not in .NET Framework 3.5

A while back Inbar Gazit blogged about a new (at the time) Orcas type System.Numeric.BigInteger.  BitInteger is intended to represent an integer of “arbitrary” precision–from 1 digit to 2,147,483,647 digits.  “Arbitrary” because realisitically approaching 2,147,483,647 will not have enough memory to store the integer.


For whatever reason, this type didn’t make it into the RTM version of .NET 3.5–it’s actually internal, not public.  I don’t know why, Inbar didn’t follow up.

Dependency Injection

Dependency injection (DI) is a form of inversion of control.  There seems to be a tendency in some circles to refer to dependency injection as inversion of control (IoC). 

Dependency injection is a form of abstraction by removing physical dependencies between classes and potentially assemblies.  This abstraction can have many different motives.  One motive is for Aspect Oriented Software Development (ASOD) where you’re abstracting shared (or cross-cutting) concerns into independent classes.  Another motive is for Test-Driven Development (TDD) where you want to be able to test each class independently of its dependencies–in which case injected dependencies are “mocked”–technically this is still AOSD because you’re separating the testing concern.

Dependency injection in .NET is most frequently implemented using interface-oriented design/programming, where a dependency of a class is on an interface.  Any class implementing that interface is then a candidate for being “injected” into the other class. There’s many ways to inject dependency, one is at time of construction the other is at time of operation. 

There are many examples of dependency injection at time of operation in the .NET Framework.  Normally when an interface is involved, dependency injection is also involved.  Serialization is a good example.  Serialization in .NET allows programmers to serialize to pretty much anything.  “Anything” being a stream.  Serialization abstracts the destination from the act of serializing and allows programmers to inject a dependency on any type of destination (media, resource, mock, etc.) simply by implementing IStream.  For example, for any given class in .NET I can “serialize” it to any stream:

            MyType myType = new MyType();
            IFormatter formatter = Configuration.CreateFormatter(typeof(myType));
            using (Stream stream = new MemoryStream())
            {
                formatter.Serialize(stream, myType);
                // TODO: something with stream.
            }

In the above example, IFormatter.Serialize(Stream, Object), uses dependency injection at time of operation to serialize to a MemoryStream object.  In no way is IFormatter.Serialize dependant on MemoryStream.  The same call could be written as follows:

            using(Stream stream = new FileStream(“file.dat”, FileMode.Create))
            {
                formatter.Serialize(stream, myType);
                // TODO: something with stream.
            }

The above form of DI is interface (and class) based, in that you need to implement a specific interface to inject as a dependency.  Another form of DI is via delegates.  You can abstract a particular class from other concerns simply by accepting a delegate.  Any class that wants to be injected simply needs to implement a method with the same signature as the required delegate.  Events are an example of this.  Any class that raises events is completely independent of any other classes that want to act as observers and subscribe to these events.  Subscribers are, in effect, are preforming dependency injection by subscribing to an event.  This form of DI is not limited to DI, it can be any delegate.  In .NET 2.0 there were many examples of this introduced.  List.ForEach, for example:

namespace Examples
{
    using System.Collections.Generic;
    public class Program
    {
        static void Main()
        {
            List<string> names = new List<string>();
            // TODO: populate names
            names.ForEach(Print);
        }
        static void Print(String name)
        {
            Console.WriteLine(name);
        }
    }
}

In this example, List<T>, of course, is completely independent from Program and Program is free to be static because there are no interface implementation requirements.

New Warning CS1060 in C# 3 (Visual Studio 2008)

Recompiling C# 2 (Visual Studio 2005) code in C# 3 (Visual Studio 2008), you may incounter a new warning that didn’t used to ocur:

Warning CS1060: Use of
        possibly unassigned field ‘fieldName’. Struct instance variables are initially unassigned if struct is unassigned.

Dealing strictly with syntax, C# let’s you declare a value type (struct) with a reference member, for example:

namespace Examples
{
    using System.Drawing;
    public static class Program
    {
        public static void Main()
        {
            LabelEntry labelEntry;
            labelEntry.Location.Point.X = 0;
        }
    }
 
    public struct LabelEntry
    {
        public LabelLocation Location;
        public String Label;
    }
 
    public class LabelLocation
    {
        public Point Point;
    }
}

Unfortunately, in C# 2, and previous, it wouldn’t give you an warning if you tried to read a value type reference member before initializing it, as in the highlighted code.


As I’ve alluded to before, syntactic correctness does not imply conceptional correctness and this warning improves syntax correctness.


If avoiding reference members in structs isn’t clear, let me know and I can do a post on that.