If you want to generate the string you can use Linq
to enumerate the properties:
MyClass test = new MyClass {
FirstName = "John",
LastName = "Smith",
};
String result = "My Name is " + String.Join(" ", test
.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(property => property.CanRead) // Not necessary
.Select(property => property.GetValue(test)));
// My Name is John Smith
Console.Write(result);
In case you want to substitute within the string (kind of formatting), regular expressions can well be your choice in order to parse the string:
String original = "My Name is @MyClass.FirstName @MyClass.LastName";
String pattern = "@[A-Za-z0-9\\.]+";
String result = Regex.Replace(original, pattern, (MatchEvaluator) ((match) =>
test
.GetType()
.GetProperty(match.Value.Substring(match.Value.LastIndexOf('.') + 1))
.GetValue(test)
.ToString() // providing that null can't be returned
));
// My Name is John Smith
Console.Write(result);
Note, that in order to get instance (i. e. not static
) property value you have to provide the instance (test
in the code above):
.GetValue(test)
so @MyClass part in the string is useless, since we can get type directly from instance:
test.GetType()
Edit: in case that some properties can return null
as value
String result = Regex.Replace(original, pattern, (MatchEvaluator) ((match) => {
Object v = test
.GetType()
.GetProperty(match.Value.Substring(match.Value.LastIndexOf('.') + 1))
.GetValue(test);
return v == null ? "NULL" : v.ToString();
}));
string.Format("My Name is {0} {1}", obj.FirstName, obj.LastName)
? Or better yet, if you're on C# 6:$"My Name is {obj.FirstName} {obj.LastName}"
?@MyClass
is useless: in order to obtain instance (i.e. notstatic
) property value you have to provide that instance:MyClass my = ... .GetValue(my);
Having that instance at hand, you can get the type (MyClass) by simplemy.GetType()