Mass Dot Net
Mass Dot Net

Reputation: 2259

C# and Reflection

I'm a brand-newbie to C#, albeit not programming, so please forgive me if I mix things up a bit -- it's entirely unintentional. I've written a fairly simple class called "API" that has several public properties (accessors/mutators). I've also written a testing console application that uses reflection to get an alphabetically list of names & types of each property in the class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using MyNamespace;      // Contains the API class

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hi");

            API api = new API(1234567890, "ABCDEFGHI");
            Type type = api.GetType();
            PropertyInfo[] props = type.GetProperties(BindingFlags.Public);

            // Sort properties alphabetically by name.
            Array.Sort(props, delegate(PropertyInfo p1, PropertyInfo p2) { 
                return p1.Name.CompareTo(p2.Name); 
            });

            // Display a list of property names and types.
            foreach (PropertyInfo propertyInfo in type.GetProperties())
            {
                Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, propertyInfo.PropertyType);
            }
        }
    }
}

Now what I need is a method that loops through the properties and concats all the values together into a querystring. The problem is that I'd like to make this a function of the API class itself (if possible). I'm wondering if static constructors have something to do with solving this problem, but I've only been working with C# for a few days, and haven't been able to figure it out.

Any suggestions, ideas and/or code samples would be greatly appreciated!

Upvotes: 2

Views: 765

Answers (1)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

This is unrelated to static constructors. You can do it with static methods:

class API {
    public static void PrintAPI() {
       Type type = typeof(API); // You don't need to create any instances.
       // rest of the code goes here.
    }
}

You can call it with:

API.PrintAPI(); 

You don't use any instances when you call static methods.

Update: To cache the result, you can either do it on first call or in an static initializer:

class API {
    private static List<string> apiCache;
    static API() {
        // fill `apiCache` with reflection stuff.
    }

    public static void PrintAPI() {
        // just print stuff from `apiCache`.
    } 
}

Upvotes: 5

Related Questions