We help IT Professionals succeed at work.

C# generics example

Medium Priority
945 Views
Last Modified: 2013-12-14
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
Comment
Watch Question

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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.