C# .NET - How to dynamically add propery in a Class in C#?

Asked By cool coder on 23-Dec-08 01:00 AM
Hi All,

I need to create property in a class dynamically.
Property names will come from database and also the total number of properies can be changed according to database value.
I have tried with CodeDome,but unable to solve.
Please suggest me.

reply - Binny ch replied to cool coder on 23-Dec-08 01:12 AM

There are several ways to do it, here's one:
Example:

using System;
using System.Collections.Generic;

public class RequestObject {
  private Dictionary mProps = new Dictionary();
  // Your regular properties
  //...
  public string this[string index] {
    get { return mProps.ContainsKey(index) ? mProps[index] : ""; }
    set {
      if (mProps.ContainsKey(index)) mProps[index] = value;
      else mProps.Add(index, value);
    }
  }
  public static void Test() {
    RequestObject obj = new RequestObject();
    obj["nobugz"] = "waz here";
    Console.WriteLine(obj["nobugz"]);
    obj["nobugz"] = "and here";
    Console.WriteLine(obj["nobugz"]);
  }
}

The mysterious "this" property is a so-called class indexer.  If you want to expand the class with class instances rather than just string, you could create a Dictionary

Dynamically Setting Properties of a Class from a Database - Binny ch replied to cool coder on 23-Dec-08 01:14 AM

Hope this will help:

public class EmployeeCollection
{
#region Start - private variables
private int _employeeID;
private string _lastName;
private string _firstName;
#endregion
public EmployeeCollection(){}
public int EmployeeID
{
get { return _employeeID; }
set { _employeeID = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}

The Employee class contains a subset of properties that correspond to the column names of the Employees table. We will now create a new constructor for the Employee class. This constructor will allow us to perform some magic. The constructor will accept a DataRow as a parameter. When the constructor is called it will set the properties of the Employee class based on the data in the DataRow parameter. By doing this, you will be able to construct a collection of employees in a very simple manner.

public Employee (System.Data.DataRow dataRow)
{
/* Enumerate all the properties of this class
* if there is a corresponding column in the data row
* set this class' property to the value of the column in the
* datarow. */

foreach( System.Reflection.PropertyInfo pi in
this.GetType().GetProperties())
{
if (pi.CanWrite)
{
try
{
if (dataRow[ pi.Name ] != null && !dataRow.IsNull( pi.Name ) )
{
pi.SetValue(
this, dataRow[ pi.Name ], null);
}
else
{
pi.SetValue(
this, null, null);
}
}
catch // DB COLUMN does not exist for this property.
{
pi.SetValue(
this, null, null);
}
}
}
}

See this link:

http://www.c-sharpcorner.com/UploadFile/dsandor/SettingClassPropsFromDb11302005064002AM/SettingClassPropsFromDb.aspx


re - Web Star replied to cool coder on 23-Dec-08 01:20 AM

look here

http://www.codeproject.com/KB/cs/FastInvokerWrapper.aspx

TRY THIS - C_A P replied to cool coder on 23-Dec-08 03:20 AM
A simple solution is to expose a field which stores a collection of name/value pairs:
Code:
    class Program
    {
        static void Main()
        {
            MyClass c = new MyClass();
            c.Properties["name"] = "value";
            // alternate syntax
            c.Properties.Add("another property", "another value");

            Console.WriteLine(c.Properties["name"]);
            Console.WriteLine(c.Properties["another property"]);
        }
    }

    class MyClass
    {
        public Hashtable Properties = new Hashtable();
    }
TRY THIS CODE - C_A P replied to cool coder on 23-Dec-08 03:22 AM
/*
ASP.NET 2.0 Unleashed (Unleashed) (Hardcover)

by Stephen Walther 

# Publisher: Sams; Bk&CD-Rom edition (June 6, 2006)
# Language: English
# ISBN: 0672328232
*/      


<%@ Page Language="C#" %>
<%@ Register TagPrefix="user" TagName="AddressForm" Src="AddressForm.ascx" %>

<script runat="server">

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        // Show Billing Address Form Results
        ltlResults.Text = "<br />Billing Street: " + AddressForm1.Street;
        ltlResults.Text += "<br />Billing City: " + AddressForm1.City;
        ltlResults.Text += "<br />Billing State: " + AddressForm1.State;
        ltlResults.Text += "<br />Billing Postal Code: " + AddressForm1.PostalCode;

        ltlResults.Text += "<br /><br />";
        
        // Show Shipping Address Form Results
        ltlResults.Text += "<br />Shipping Street: " + AddressForm2.Street;
        ltlResults.Text += "<br />Shipping City: " + AddressForm2.City;
        ltlResults.Text += "<br />Shipping State: " + AddressForm2.State;
        ltlResults.Text += "<br />Shipping Postal Code: " + AddressForm2.PostalCode;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
        html
        {
            background-color:silver;
            font:14px Georgia,Serif;
        }
        .content
        {
            background-color:white;
            width:600px;
            margin:auto;
            padding:20px;
        }
        .addressLabel
        {
            float:left;
            width:100px;
            padding:5px;
            text-align:right;
        }
        .addressField
        {
            float:left;
            padding:5px;
        }
        .clear
        {
            clear:both;
        }

    </style>
    <title>Checkout</title>
</head>
<body>
    <form id="form1" runat="server">
    <div class="content">
    
    <user:AddressForm
        id="AddressForm1"
        Title="Billing Address"
        Runat="server" />

    <br />

    <user:AddressForm
        id="AddressForm2"
        Title="Shipping Address"
        Runat="server" />

    <br />
    
    <asp:Button
        ID="btnSubmit"
        Text="Submit Form"
        OnClick="btnSubmit_Click" 
        Runat="server" />

    <hr />

    <asp:Literal
        id="ltlResults"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>


<%--
<%@ Control Language="C#" ClassName="AddressForm" %>
<script runat="server">

    public string Title
    {
        get return ltlTitle.Text; }
        set ltlTitle.Text = value; }
    }

    public string Street
    {
        get return txtStreet.Text; }
        set txtStreet.Text = value; }
    }

    public string City
    {
        get return txtCity.Text; }
        set txtCity.Text = value; }
    }

    public string State
    {
        get return txtState.Text; }
        set txtState.Text = value; }
    }

    public string PostalCode
    {
        get return txtPostalCode.Text; }
        set txtPostalCode.Text = value; }
    }
    
</script>

<fieldset>
<legend>
    <asp:Literal 
        ID="ltlTitle"
        Text="Address Form" 
        runat="server" />
</legend>

<div class="addressLabel">
<asp:Label  
    ID="lblStreet"
    Text="Street:"
    AssociatedControlID="txtStreet"
    Runat="server" />
</div>
<div class="addressField">
<asp:TextBox
    ID="txtStreet"
    Runat="server" />
<asp:RequiredFieldValidator
    ID="reqStreet"
    Text="(required)"
    ControlToValidate="txtStreet"
    Runat="server" />    
</div>

<br class="clear" />

<div class="addressLabel">
<asp:Label  
    ID="lblCity"
    Text="City:"
    AssociatedControlID="txtCity"
    Runat="server" />
</div>
<div class="addressField">
<asp:TextBox
    ID="txtCity"
    Runat="server" />
<asp:RequiredFieldValidator
    ID="reqCity"
    Text="(required)"
    ControlToValidate="txtCity"
    Runat="server" />    
</div>

<br class="clear" />

<div class="addressLabel">
<asp:Label  
    ID="lblState"
    Text="State:"
    AssociatedControlID="txtState"
    Runat="server" />
</div>
<div class="addressField">
<asp:TextBox
    ID="txtState"
    Runat="server" />
<asp:RequiredFieldValidator
    ID="reqState"
    Text="(required)"
    ControlToValidate="txtState"
    Runat="server" />    
</div>

<br class="clear" />

<div class="addressLabel">
<asp:Label  
    ID="lblPostalCode"
    Text="Postal Code:"
    AssociatedControlID="txtPostalCode"
    Runat="server" />
</div>
<div class="addressField">
<asp:TextBox
    ID="txtPostalCode"
    Runat="server" />
<asp:RequiredFieldValidator
    ID="RequiredFieldValidator1"
    Text="(required)"
    ControlToValidate="txtPostalCode"
    Runat="server" />    
</div>

<br class="clear" />

</fieldset>        
--%> 

TRY THIS LINK - C_A P replied to cool coder on 23-Dec-08 03:25 AM

http://p2p.wrox.com/c-2005/71934-how-dynamically-add-propery-class-c.html

http://www.codeproject.com/script/Forums/View.aspx?fid=446155&msg=2218813

http://www.agiledeveloper.com/blog/CommentView.aspx?guid=260d7334-ce2b-4593-a210-b35b54fc5fce

 

Re :: How to dynamically add property in a class in C# - Shailendrasinh Parmar replied to cool coder on 23-Dec-08 06:16 AM

See the following article by Dave Elliott on Creating property dynamically

http://www.codeproject.com/KB/dotnet/Dynamic_Properties.aspx

Hope this helps.