Generic class

L

Luigi

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

Thanks a lot.
 
S

Steph

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{;}
}
}
 
S

Steph

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
 
M

Marc Gravell

That doesn't use generics; while it will work (typos aside), it isn't
exactly going to help much.
 
M

Marc Gravell

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
 
L

Luigi

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
 
S

Stanimir Stoyanov

Luigi, please see your previous post about this. It is not an implementation
using generics but should fit your requirements.
 
A

Anthony Jones

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top