Alex Zhulin
Alex Zhulin

Reputation: 1305

C# Property in class with not defined type

I want to create some class in C# (let's say it class Attribute)

public class Attribute
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

The entity of this class will have ID, Name and Value properties.

The main problem is that I want to save in property Value different types of data: String, int, double, DateTime and so on.

What is the best way to make solutions like this?

Upvotes: 0

Views: 1845

Answers (2)

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

You are looking for a generic Type?

public class Attribute<T>
{
    public int ID {get; set;}
    public string Name { get; set; }
    public T Value { get; set; }
}

Edited:

public void SomeMethod()
{
    var attribute = new Attribute<int>(){ ID = 1, Name = "TheName", Value = 46 };
}

Upvotes: 6

Amit
Amit

Reputation: 17

Usuage will be like this

    int result =10;
    Attribute<int> objAttribute = new Attribute<int>();
    objAttribute.value = result;

    string strResult ="Sucess";
    Attribute<string> objAttribute1 = new Attribute<string>();
    objAttribute1.value = strResult ;

Upvotes: 0

Related Questions