Generic class

  • Thread starter Thread starter Luigi
  • Start date Start date
L

Luigi

Hi all,
how can create a generic class tha has a "value" property that can be int or
string?

Thanks a lot.
 
Luigi said:
Hi all,
how can create a generic class tha has a "value" property that can be int or
string?

Thanks a lot.
public class test
{
public object a_param
{
get{;}
set{;}
}
}
 
Luigi said:
Is the same writing?

public class Test<T>
{
public T value;
}

why not ! all depend of your use !
your can use one of this two ways.

the code class goto define the good way
 
That doesn't use generics; while it will work (typos aside), it isn't
exactly going to help much.
 
You can't do much to restrict the available types to int or string, but
if you are happy to allow any type:

public class Foo<T> {
public T Value {get;set;}
}

or in C# 2.0:

public class Foo<T> {
private T value;
public T Value {
get {return this.value;}
set {this.value = value;}
}

The only way to disallow other types would be to use a type inintializer
- but it probably isn't worth it. There are such things as generic
constraints, but none that would fit here.

Marc
 
Marc Gravell said:
You can't do much to restrict the available types to int or string, but
if you are happy to allow any type:

public class Foo<T> {
public T Value {get;set;}
}

or in C# 2.0:

public class Foo<T> {
private T value;
public T Value {
get {return this.value;}
set {this.value = value;}
}

The only way to disallow other types would be to use a type inintializer
- but it probably isn't worth it. There are such things as generic
constraints, but none that would fit here.

Thank you Marc, this sounds fine.

Luigi
 
Luigi, please see your previous post about this. It is not an implementation
using generics but should fit your requirements.
 
Marc Gravell said:
You can't do much to restrict the available types to int or string, but if
you are happy to allow any type:

public class Foo<T> {
public T Value {get;set;}
}

or in C# 2.0:

public class Foo<T> {
private T value;
public T Value {
get {return this.value;}
set {this.value = value;}
}

The only way to disallow other types would be to use a type inintializer -
but it probably isn't worth it. There are such things as generic
constraints, but none that would fit here.

I've used IConvertible as a constraint. Not as specific as int and string
but it does narrow things down considerably without excluding either of
those two.
 
Back
Top