9

I have a class like

public class MyClass {

  public string FirstName {get; set;}
  public string LastName {get; set;}

}

The case is, I have a string text like,

string str = "My Name is @MyClass.FirstName @MyClass.LastName";

what I want is to replace @MyClass.FirstName & @MyClass.LastName with values using reflection which are assigned to objects FirstName and LastName in class.

Any help please?

3
  • Are you looking for 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}"?
    – Kvam
    Commented Nov 12, 2015 at 14:57
  • i want to do using reflection not string.Format
    – Aqdas
    Commented Nov 12, 2015 at 15:00
  • @MyClass is useless: in order to obtain instance (i.e. not static) property value you have to provide that instance: MyClass my = ... .GetValue(my); Having that instance at hand, you can get the type (MyClass) by simple my.GetType() Commented Nov 12, 2015 at 15:54

5 Answers 5

9

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(); 
 }));
10
  • Great Solution. I beleive using it with regular expression will be more efficient than looping objects. I have one question. If i do not know what type of my class is i.e. it can be MyCar or MyClass or MyHome, and i am also unaware of what exactly string is, in this case, any type of class can find and replace its properties in string which i provided on object original. any thoughts for this?
    – Aqdas
    Commented Nov 12, 2015 at 16:02
  • @Aqdas: "MyClass" string as well as "MyCar" or "MyHome" is not enough; in order to read instance property you have to provide the instance. Imagine, that you have, say, three MyClass instances - my1, my2, my3 with different properties values. What instance should be used? In the code above for each match you have to provide that instance (put the logic when I've put test) Commented Nov 12, 2015 at 16:09
  • I am providing it instance as generic parameter to function by name T object and it has objects and is instantiated.
    – Aqdas
    Commented Nov 12, 2015 at 16:11
  • @Aqdas: then could you provide the function's signature? Something like String MyFunc(String line, Object instance); Commented Nov 12, 2015 at 16:14
  • i am done with it and this solution worked perfect for me, just one question i would like to ask you is // providing that null can't be returned can you explain this in detail please? or any solution for this?
    – Aqdas
    Commented Nov 12, 2015 at 16:17
8

First of all, I'd advice against using reflection when other options such as string.Format is possible. Reflection can make your code less readable and harder to maintain. Either way, you could do it like this:

public void Main()
{
    string str = "My Name is @MyClass.FirstName @MyClass.LastName";
    var me = new MyClass { FirstName = "foo", LastName = "bar" };
    ReflectionReplace(str, me);
}

public string ReflectionReplace<T>(string template, T obj)
{    
    foreach (var property in typeof(T).GetProperties())
    {
        var stringToReplace = "@" + typeof(T).Name + "." + property.Name;
        var value = property.GetValue(obj);
        if (value == null) value = "";
        template = template.Replace(stringToReplace, value.ToString());
    }
    return template;
}

This should require no additional changes if you want to add a new property to your class and update your template string to include the new values. It should also handle any properties on any class.

4
  • good answer, One more question i would like to ask here is, suppose i do not know what is the type of object i.e. what is name of class, and how many objects i need to replace? So in this case, I want that if a type is MyCar or a type is MyHome, then i would like that all values which are like MyClass.FirstName get updated in string text object,
    – Aqdas
    Commented Nov 12, 2015 at 15:24
  • I mean, i do not know the type of class & and also do not know what is in string text (which i need to replace) only what i know is, if string text has all properties of the same time, then they need to be replaced with their assigned value.
    – Aqdas
    Commented Nov 12, 2015 at 15:25
  • I updated the answer to handle objects of any type (that has properties.)
    – Kvam
    Commented Nov 12, 2015 at 15:30
  • Older versions of .NET use ...GetValue(obj, null);
    – scotru
    Commented Jun 2, 2017 at 8:01
2

Using Reflection you can achieve it as shown below

MyClass obj = new MyClass() { FirstName = "Praveen", LaseName = "Paulose" };

        string str = "My Name is @MyClass.FirstName @MyClass.LastName";

        string firstName = (string)obj.GetType().GetProperty("FirstName").GetValue(obj, null);
        string lastName = (string)obj.GetType().GetProperty("LaseName").GetValue(obj, null);

        str = str.Replace("@MyClass.FirstName", firstName);
        str = str.Replace("@MyClass.LastName", lastName);

        Console.WriteLine(str);

You are first finding the relevant Property using GetProperty and then its value using GetValue

UPDATE

Based on further clarification requested in the comment

You could use a regex to identify all placeholders in your string. i.e. @MyClass.Property. Once you have found them you can use Type.GetType to get the Type information and then use the code shown above to get the properties. However you will need the namespace to instantiate the types.

4
  • Good answer, I have a question here regarding this solution. is there any approach, that instead of using String.Replace i can do something like which change @MyClass.FirstName within same text? For example, Myclass has 100+ properties and sometime text has three values or some time 50+ . so is there anyway, that all these values available in text replaced by the value which property has assigned? Thanks for your reply
    – Aqdas
    Commented Nov 12, 2015 at 15:12
  • @Aqdas What is your question? Commented Nov 12, 2015 at 15:14
  • @Aqdas You could use a regex to identify all placeholders in your string. i.e. MyClass.Property. Once you have found them you can use Type.GetType to get the Type information and then use the code shown above to get the properties. However you will need the namespace to instantiate the types. Commented Nov 12, 2015 at 15:34
  • @Parveen any example please if you can provide me for replacing multiple objects using regex?
    – Aqdas
    Commented Nov 12, 2015 at 15:53
0

Although this is five years old, I found it useful.

Here is my adaptation of Dmitry Bychenko's that also dives into any JSON fields as well.

Only works on one level, but I'll make it recursive at some point.

Regex _replacementVarsRegex = new Regex(@"\{\{([\w\.]+)\}\}", RegexOptions.Compiled);
var result = "string with {{ObjectTypeName.PropertyName}} and json {{ObjectTypeName.JsonAsStringProperty.JsonProperty}}";
string ReplaceFor(object o) => _replacementVarsRegex.Replace(result, match =>
{
    if (o == null) return match.Value;
    var typeName = match.Value.Substring(0, match.Value.IndexOf('.')).TrimStart('{');
    var type = o.GetType();
    if (typeName != type.Name) return match.Value;
    var name = match.Value.Substring(match.Value.LastIndexOf('.') + 1).TrimEnd('}');
    var propertyInfo = type.GetProperty(name);
    var value = propertyInfo?.GetValue(o);
    var s = value?.ToString();
    if (match.Value.Contains(".Metadata."))
    {
        var jsonProperty = type.GetProperty("Metadata");
        var json = jsonProperty?.GetValue(o)?.ToString() ?? string.Empty;
        if (!string.IsNullOrWhiteSpace(json))
        {
            // var dObj = JsonConvert.DeserializeObject(json);
            var jObj = JObject.Parse(json);
            var val = jObj[name].Value<string>();
            s = val;
        }
    }

    return s ?? match.Value;
});

result = ReplaceFor(object1);
result = ReplaceFor(object2);
//...
result = ReplaceFor(objectn);

//remove any not answered, if desired
result = _replacementVarsRegex.Replace(result, string.Empty);

improvement suggestions welcome!

0

Working on a project recently I ended up needing something similar. The requirement was to use a placeholder format that wouldn't naturally occur in our text @obj.property may have so @obj.property@ was used. Also, handling of cascading tokens (tokens depending on tokens) and handling of data coming from IEnumerable, such as: ["Cat", "Dog", "Chicken"] needing to displayed in the text as "Cat, Dog, Chicken".

I've created a library and have a NuGet package to get this functionality into your code a little quicker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.