how to get a property of instant?

mc 1,921 Reputation points

I have class :

public class MyClass1{
public string Val{get;set;}
public int Id{get;set;}
MyClass1 mc=new MyClass1{Id=1};

how to get the value of Id of mc ?

I have a string string col="Id"

and I want get the value of mc the property is in col

in javascript I can do :

var val=mc[col];

in c# can I get it?

Microsoft Technologies based on the .NET software framework.
1,140 questions
A set of technologies in the .NET Framework for building web applications and XML web services.
3,121 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: The period of time during which a program is being executed in a computer.
996 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 94,021 Reputation points

    Try one of solutions:

    PropertyInfo p = typeof( MyClass1 ).GetProperty( col );
    object result = p.GetValue( mc );

    The result can be casted to int.


    switch( col )
    case "Id":
        int id = mc.Id;
        // . . .
    case "Val":
        string val = mc.Val;
        // . . .
    1 person found this answer helpful.
    0 comments No comments

  2. davidjohnson 0 Reputation points

    To get a property of an instance in C#, you need to access the property using the dot (.) notation. Here's an example:

    csharpCopy code
    // Create an instance of a class
    var myInstance = new MyClass();
    // Access the property of the instance
    var propertyValue = myInstance.PropertyName;

    In the above code, MyClass is a class that has a property named PropertyName. By using the dot notation (myInstance.PropertyName), you can access the value of that property.

    Make sure to replace MyClass with the actual name of your class and PropertyName with the name of the property you want to access.


    David johnson

    0 comments No comments