how to get a property of instant?

mc 1,921 Reputation points
2023-05-16T09:04:59.37+00:00

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?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
1,140 questions
ASP.NET Core
ASP.NET Core
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
    2023-05-16T11:56:37.6633333+00:00

    Try one of solutions:

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

    The result can be casted to int.

    Or:

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

  2. davidjohnson 0 Reputation points
    2023-05-16T13:42:40.41+00:00

    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.

    Regards

    David johnson

    0 comments No comments