Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding properties dynamically to a class

Tags:

c#

In my class I have private variables and properties like this.

private string _itemCOde=string.Empty;
private string  _itemName=string.Empty;

public string ItemCode
{
    get { return _itemCode; }
    set { _itemCode = value == null ? value : value.Trim();}
}

public string ItemName
{
    get { return _itemName; }
    set { _itemName = value == null ? value : value.Trim();}
}

According to this properties I create Item objects after selecting the data from the sql table.

Now, if database table altered and add a new column called cost, then I have to add another property to the class. Without adding new properties to the class is there any way do declare properties according to the table fields dynamically.

like image 637
Snj Avatar asked Jun 01 '11 03:06

Snj


People also ask

How do I add a property to a class dynamically?

You can add a property to a class dynamically. But that's the catch: you have to add it to the class. A property is actually a simple implementation of a thing called a descriptor. It's an object that provides custom handling for a given attribute, on a given class.

How do I add an attribute to a class in Python?

Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.

What is dynamic property?

Theoretically, it can be defined as the ratio of stress to strain resulting from an oscillatory load applied under tensile, shear, or compression mode.


1 Answers

You could use an ExpandoObject:

Represents an object whose members can be dynamically added and removed at run time.

dynamic expando = new ExpandoObject();
expando.Cost= 42.0;
expando.ItemName = "Shoes";
like image 150
BrokenGlass Avatar answered Nov 15 '22 14:11

BrokenGlass