webnoob
webnoob

Reputation: 15934

Using a function to create an instance of a class based on the type passed through

I have this method:

internal static void AssignNewArrayItem(ref Xml.CLASSNAME[] Items, Xml.CLASSNAME Item)
{
    if (Items != null)
    {
        Array.Resize(ref Items, Items.Length + 1);
        Items[Items.Length - 1] = Item;
    }
    else
        Items = new Xml.CLASSNAME[] { Item };
}

At the moment I have about 10 overloaded versions where CLASSNAME is different but they all do the exact same thing. Is there any way I can have CLASSNAME as a generic object and cast the vars to achieve the same result?

I am open to other suggestions to acheive the same result if I am going about this in the wrong way as well.

Upvotes: 0

Views: 77

Answers (4)

Yochai Timmer
Yochai Timmer

Reputation: 49221

You can use generic constraints, the constraint will only accept objects that inherit from the class Xml.CLASSNAME

internal static void AssignNewArrayItem<T>(ref T[] Items, T Item) where T: Xml.CLASSNAME
{
    if (Items != null)
    {
        Array.Resize(ref Items, Items.Length + 1);
        Items[Items.Length - 1] = Item;
    }
    else
        Items = new Xml.CLASSNAME[] { Item };
}

Upvotes: 0

Botz3000
Botz3000

Reputation: 39600

Have you tried this:

internal static void AssignNewArrayItem<T>(ref T[] Items, T Item)
{
    if (Items != null)
    {
        Array.Resize(ref Items, Items.Length + 1);
        Items[Items.Length - 1] = Item;
    }
    else
        Items = new T[] { Item };
}

I think using a List<T> would be the better option here though.

Upvotes: 2

Justin Pihony
Justin Pihony

Reputation: 67065

I believe this should work. As you suggested yourself, just use generics. To get this in your method, you simply change anywhere there is going to be a variable type with the value between the brackets (it does not have to be T, but that is the convention)

internal static void AssignNewArrayItem<T>(ref T[] Items, T Item)
{
    if (Items != null)
    {
        Array.Resize(ref Items, Items.Length + 1);
        Items[Items.Length - 1] = Item;
    }
    else
        Items = new T { Item };
}

You should possibly put constraints on the method, though. Do you have a base type you are expecting? If so, you could do this:

internal static void AssignNewArrayItem<T>(ref T[] Items, T Item) 
    where T : <base class name>

Upvotes: 1

daryal
daryal

Reputation: 14919

internal static void AssignNewArrayItem<T>(ref T[] Items, T Item)
    {
        if (Items != null)
        {
            Array.Resize(ref Items, Items.Length + 1);
            Items[Items.Length - 1] = Item;
        }
        else
            Items = new T[] { Item };
    }

Upvotes: 2

Related Questions