user2818430
user2818430

Reputation: 6029

Add dynamic property to .NET classes

Is it possible to add my own custom property to any type of object?

In this example the object is List but I mean for any kind of object (.NET or custom ones).

For example extend List<string> to add an extra property called MyProperty:

List<string> myList = new List<string>();
myList.MyProperty = "some value";

then call a method ProcessList(List<string> list):

ProcessList(myList);

public void ProcessList(List<string> list)
{
  // get the custom property value

  string myprop = list.MyProperty.ToString();
  ....................
  do other work
}

Upvotes: 1

Views: 167

Answers (2)

James Johnson
James Johnson

Reputation: 46047

Not the way you're describing. Extension methods are probably the closest you'll get.

public static class QueryExtensions
{
    public static bool HasMapping(this Demand role)
    {
        return role.DemandMappings.Count > 0;
    }
}

You would use the above example like this:

var role = GetDemand(Request.QueryString["id"]);
if (role != null)
{
    var mapped = role.HasMapping();
}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

No. There is no "extension property" implementation in .NET. Extension methods are more of a compiler trick, and only work as static methods because they do not require their own state (at least should not).

A property would require a backing field, which would require other functionality in order to implement properly.

Note that certain frameworks do support this. For example, if your object derives from DependencyObject, you could use Attached Properties to implement this functionality.

Upvotes: 1

Related Questions