How to convert a property of class base on its type

Forums C#How to convert a property of class base on its type
Staff asked 1 year ago

Answers (1)

Add Answer
krishna kukadiya Marked As Accepted
Staff answered 1 year ago

To convert a property of a class based on its type, you can use conditional statements or switch statements to handle each data type appropriately. Here’s an example that demonstrates how to convert a property based on its type using C#:

public class MyClass
{
    public string StringProperty { get; set; }
    public int IntProperty { get; set; }
    public DateTime DateTimeProperty { get; set; }
    // Other properties...

    public object ConvertProperty(object value)
    {
        if (value is string stringValue)
        {
            // Convert string value
            return Convert.ToString(stringValue);
        }
        else if (value is int intValue)
        {
            // Convert int value
            return Convert.ToInt32(intValue);
        }
        else if (value is DateTime dateTimeValue)
        {
            // Convert DateTime value
            return Convert.ToDateTime(dateTimeValue);
        }
        else
        {
            // Handle other types or throw an exception if necessary
            throw new NotSupportedException("Unsupported property type.");
        }
    }
}

In the above example, the ConvertProperty method accepts an object value and checks its type using conditional statements (if, else if). Depending on the type of the property, it performs the appropriate conversion using the Convert class or any other custom conversion logic you may need.

You can then call the ConvertProperty method for a specific property of an instance of the MyClass class to convert its value based on its type.

MyClass myObject = new MyClass();
myObject.StringProperty = "Hello";
myObject.IntProperty = 123;
myObject.DateTimeProperty = DateTime.Now;

string convertedString = (string)myObject.ConvertProperty(myObject.StringProperty);
int convertedInt = (int)myObject.ConvertProperty(myObject.IntProperty);
DateTime convertedDateTime = (DateTime)myObject.ConvertProperty(myObject.DateTimeProperty);

Console.WriteLine(convertedString); // Output: "Hello"
Console.WriteLine(convertedInt); // Output: 123
Console.WriteLine(convertedDateTime); // Output: Current date and time

By using conditional statements or switch statements and performing the appropriate conversions based on the property’s type, you can convert the property values accordingly.

Subscribe

Select Categories