• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 889
  • Last Modified:

C# generics example

What is the exact syntax to be used for a method using generics feature?

Response <Z> MyMethod( T t, U u) {
will the above syntax work?
Basically The Response type can be any derived type from a basic Response Type(class). The arguments T and U also can be any derived types from a basic type/class respectively.
Are there good online docs for genercis in C#
Thanks in advance
1 Solution
You are talking about constraints in generic type parameters - see http://msdn.microsoft.com/en-us/library/d5x73970.aspx - here are the basics:

Ensure T is or is derived from class - where T : Person  
Ensure T implements interface IInterface - where T : ISerializable
Ensure T is newable (e.g. use new T() in function) - where T : new()
Use multiple parameters - where T: new(), ICloneable, IComparable<U>
You can declare your generic function as follows:

        public Z MyMethod<Z, T, U>(T t, U u)
            where Z : Response
            where T : MyClass
            where U : MyOtherClass

Open in new window


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now