Ben
Ben

Reputation: 2465

How to call a function from an object got from generic method?

I'm relatively new to C# so please bear with me.

I don't know how to perform this operation more efficiently.

public static void Foo<T>(LinkedList<T> list)
{
    foreach (Object o in list)
    {
        if (typeof(o) == typeof(MyClass1))
            (MyClass1)o.DoSomething();
        else if (typeof(o) == typeof(MyClass2))
            (MyClass2)o.DoSomething();

        ...
      }
  }

I would like to do something like this, or something more efficient than what I am doing now. by efficient I mean that program will run faster.

public static void Foo<T>(LinkedList<T> list)
{
    foreach (Object o in list)
    {
        o.DoSomething();
      }
  }

Thank you for your help.

Upvotes: 0

Views: 55

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126982

You're looking for a polymorphic behavior.

abstract class Base // could also simply be interface, such as ICanDoSomething
{
     public abstract void DoSomething();
}

class MyClass1 : Base
{
    public override void DoSomething() { /* implement */ }
}

In this case, you can define your method to constraint T to Base, and then you are allowed to use the method defined against Base but implemented by each derived class.

public static void Foo<T>(LinkedList<T> list) where T : Base // or T : ICanDoSomething
{    
    foreach (T item in list)
    {
         item.DoSomething();
    }
}

You generally do not want to resort to type checking inside methods, as you seem to have already realized. It's not particularly about efficiency as it is about good programming practice. Each time you add a new class, you have to come back to the method and add yet another check, which violates all kinds of solid programming practices.

Upvotes: 2

L.B
L.B

Reputation: 116178

public interface IDoSomething
{
    void DoSomething();
}

public static void Foo<T>(LinkedList<T> list) where T : IDoSomething
{
    foreach (T o in list)
    {
        o.DoSomething();
    }
}

Upvotes: 1

Samich
Samich

Reputation: 30175

Implement some interface for your types

public interface IMyType
{
    void DoSomething();
}

public class MyType1 : IMyType
{
    public void DoSomething() { }
}

public class MyType2 : IMyType
{
    public void DoSomething() { }
}

and use like

public static void Foo<T>(LinkedList<T> list) where T: IMyType
{
    foreach (T o in list)
    {
        o.DoSomething();
      }
  }

Upvotes: 2

Related Questions