#727 – Get a List of All Namespaces in an Assembly

While you can’t explicitly get a list of all namespaces within a .NET assembly, you can iterate through all types in the assembly and build up a list of namespaces.

Below is some sample code that organizes all types in an assembly, by namespace.

        static void Main()
        {
            // Build list of all types :
            //   SortedList<namespace-name, SortedList<type-name, Type>>

            SortedList<string, SortedList<string, Type>> myTypeList =
                ExtractListOfTypes(Assembly.GetExecutingAssembly());

            DumpTypeList(myTypeList);
        }

        private static SortedList<string, SortedList<string, Type>> ExtractListOfTypes(Assembly assem)
        {
            SortedList<string, SortedList<string, Type>> theList =
                new SortedList<string, SortedList<string, Type>>();

            foreach (Type t in assem.GetTypes())
            {
                // Add namespace if it's not already in list
                if (!theList.ContainsKey(t.Namespace))
                    theList.Add(t.Namespace, new SortedList<string, Type>());

                // And add type under appropriate namespace
                theList[t.Namespace].Add(t.FullName, t);
            }

            return theList;
        }

        private static void DumpTypeList(SortedList<string, SortedList<string, Type>> theList)
        {
            foreach (KeyValuePair<string,SortedList<string,Type>> kvp in theList)
            {
                Console.WriteLine(string.Format("Namespace: [{0}]", kvp.Key));

                foreach (KeyValuePair<string, Type> kvpInner in kvp.Value)
                {
                    Console.WriteLine(string.Format("  Type: [{0}]", ((Type)kvpInner.Value).FullName));
                }

                Console.WriteLine();
            }
        }

727-001

Advertisements

#726 – Listing all Types within a Namespace

You can’t directly list out all types within a namespace.  But you can get all types within a particular assembly and then filter out only the types that match a particular namespace.

        static void Main()
        {
            // Dump all types from in a specified namespace
            DumpTypesForNamespace(Assembly.GetExecutingAssembly(), "ConsoleApplication1");
            DumpTypesForNamespace(Assembly.GetExecutingAssembly(), "ConsoleApplication1.Dog");

            int i = 1;
        }

        private static void DumpTypesForNamespace (Assembly assem, string theNamespace)
        {
            Console.WriteLine(string.Format("[{0}]", theNamespace));

            foreach (Type t in assem.GetTypes())
            {
                if (t.Namespace == theNamespace)
                {
                    string dump =
                        string.Format("{0}\n  ({1} in {2})\n", t.FullName, TypeIndicator(t), t.Namespace);

                    Console.WriteLine(dump);
                }
            }
            Console.WriteLine("\n");
        }

        private static string TypeIndicator(Type t)
        {
            string typeIndicator = "?";

            if ((t.BaseType != null) &&
                (t.BaseType.FullName == "System.MulticastDelegate"))
                typeIndicator = "delegate";

            else if (t.IsClass)
            {
                if (t.IsNested)
                    typeIndicator = "Nested class";
                else
                    typeIndicator = "class";
            }
            else if (t.IsInterface)
                typeIndicator = "interface";

            else if (t.IsValueType)
                typeIndicator = "struct";

            else if (t.IsEnum)
                typeIndicator = "enum";

            return typeIndicator;
        }

726-002

#699 – Types Are Implicitly Internal

When you define a type in C#, you can define its accessibility as either public or internal.  Public types are visible to all code.  Internal types are visible only to code within the same assembly.

By default, if you don’t include an access modifier when defining a type, the type’s accessibility will be internal.

In the example below, the Dog class will be visible only to code within the same assembly.

    // No access modifier => type is internal, visible
    //   only to code within the same assembly.
    class Dog
    {
        // Public properties
        public string Name { get; set; }
        public int Age { get; set; }

        // Instance constructor
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public void Bark()
        {
            Console.WriteLine("Woof");
        }
    }

#459 – Assigning a Value of a Different Type to an enum

You can convert to an enum value from its underlying type by casting the underlying type (e.g. int) to the enum type.  You can also assign a value of a different type, one that does not match the underlying type, as long as the cast succeeds.

        // By default stored as int, with values 0,1,2,3
        public enum Mood { Crabby, Happy, Petulant, Elated };

        static void Main()
        {
            byte moodValue = 3;
            Mood mood;

            // Works (byte -> int)
            mood = (Mood)moodValue;

            // Also works, since cast converts value to 2 (Petulant)
            double moodValue2 = 2.1;
            mood = (Mood)moodValue2;
        }

#205 – Five Kinds of Types That Are User-Definable

C# allows you to create new types.  There are five kinds of types that you can define.

A class is a data structure containing data and its associated behavior.  You can create an instance of a class using the new keyword, giving you an object.

A struct is similar to a class, containing data and behavior.  But an instance of a struct is created on the stack, rather than the heap.

An interface defines a set of methods, properties and events that a class can implement.  It is just a description of what a class needs to implement, in order to fully implement the interface.

A delegate is a definition of a method signature, which includes the data type of the method’s parameters and return value.  An instance of a delegate type references a specific method.

An enum type represents a set of named constants.

#31 – Value Types and Reference Types

All types in C#, whether built-in or user-defined custom types, can be categorized as either value types or reference types.

  • Value types
    • Derive from System.ValueType (which derives from System.Object)
    • Allocated on the stack  (unless declared inside a reference type)
    • Value type variable contains value directly
    • Assignment makes a copy of the value
    • Passed by value (a copy is made)
    • Not garbage collected–die when they go out of scope
    • Either struct or enum
    • Sealed–can’t inherit from them
  • Reference types
    • Derive from System.Object or another reference type
    • Allocated on the heap
    • Reference type variable contains a reference (pointer) to the object’s contents (or contains null)
    • Assignment creates a new reference to the original object
    • Passed by reference  (pointer to object is passed)
    • Garbage collected
    • One of: class, delegate, array or interface
    • Support inheritance

#30 – Types, Variables, Values, Instances

In C#, a type dictates what kind of values can be stored in a variable.  A variable is a storage location for some data.  Every variable is an instance of a specific type and will have a value that can change during the lifetime of a program.

Constants are variables whose values do not change.  They also have a specific type.

Expressions resolve to a particular value when they are evaluated.  They also have a specific type.

There are a number of built-in types in C#  (e.g. int, float) as well as constructs that allow you to create your own types (e.g. class, enum).