Click here to Skip to main content
15,900,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All

C#
namespace MyNamespace
{
    public class MyClass<string>
    {
        //my code goes here
    }
    public class Demo
    {
        public static void main()
        {
            MyClass<int> obj = new MyClass<int>();
        }
    }
}


if I created object like this, it is not giving error why? what does it mean exactly?

if I created class like

C#
public class MyClass<t>
{
    //my code goes here
}


means dynamically we can pass any type to members which uses type as "T", apart from this is there any other reason? am getting confusion on this?

Thank u
Posted
v2

Before 'adventuring' into Generics land, I strongly advice you reading some documentation. You may start, for instance with: An Introduction to C# Generics[^].
 
Share this answer
 
That should give an error, you're not allowed to do
C#
public class MyClass<string>


The type parameter declaration must be an identifier, not a type.

Check what you're compiling again to make sure you're actually compiling what you think you are.

Hope this helps,
Fredrik
 
Share this answer
 
Refer - [MSDN] Generics (C# Programming Guide)[^]
Quote:
Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:
 
Share this answer
 
The second class which you declare is a generic class

XML
public class MyClass<t>
{
    //my code goes here
}


This class datatype defined when its object are created.

However if you are creating class of string type and then create an object of int type it will definitely gives you an error.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900