JimZ
JimZ

Reputation: 1202

C# To use generice type delegate in class also has generic type

I would like to make a class that accept Type as parameter, and in the meantime, I want to make a delegate which is also generic typed. The sample code is as follow. I think it should work, the OnGo delegate receives the Type as TypeAsParam from class declaration. However, the commented line is wrong. Does someone know how to fix this? Thank you all guys :)

public delegate void OnGo<TypeInDel>(TypeInDel obj);

public class MyClass<TypeAsParam>
{
    public OnGo<TypeAsParam> MyDelegate;
    public void Msg<TypeAsParam>()
    {
        TypeAsParam msg;
        MyDelegate(msg); //here is wrong in VS editor, says cannot cast msg to TypeAsParam(not TypeInDel)
    }
}

Upvotes: 1

Views: 61

Answers (4)

Justin Harvey
Justin Harvey

Reputation: 14682

This is because it is seeing two separate declaration of your generic type, TypeAsParam, and thinks they are different things. I have also added a default value for the msg object to avoid a secondary compiler error. Change to:

public delegate void OnGo<TypeInDel>(TypeInDel obj);

public class MyClass<TypeAsParam>
{
    public OnGo<TypeAsParam> MyDelegate;

    public void Msg()
    {
      TypeAsParam msg = default(TypeAsParam);
      MyDelegate(msg); //here is wrong in VS editor, says cannot cast msg to TypeAsParam(not TypeInDel)
    }
}

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

It works for me by applying constraint on it :

 public delegate void OnGo<TypeInDel>(TypeInDel obj);

        public class MyClass<TypeAsParam> where TypeAsParam : new()
        {
            public OnGo<TypeAsParam> MyDelegate;

            public void Msg()
            {
                TypeAsParam msg =  new TypeAsParam();
                MyDelegate(msg); 
            }
        }

Upvotes: 1

puko
puko

Reputation: 2980

Apparently this method is inside a class that already specifies type . That means methods of your generic class are automatically generic too.

public class MyClass<TypeAsParam>
      {
         public OnGo<TypeAsParam> MyDelegate;

         public void Msg(TypeAsParam msg)
         {
            MyDelegate(msg); 
         }
      }

Upvotes: 0

Alex Voskresenskiy
Alex Voskresenskiy

Reputation: 2233

The problem is with your Msg method. In it you define new TypeParameter and so compiler cannot be sure that TypeAsParam from class and TypeAsParam from method are same. You need to remove <TypeAsParam> from message or to make some constraints.

Also, you need to init your msg like this:

var msg = default(TypeAsParam)

Upvotes: 5

Related Questions