0

I would like to make a function that converts a string to an object. In my case this is for IFC reading function, I have many functions to read different strings to <T>

Until now, I have something like that :

public void convertIfcCartesianPoint(string inputLine)
{
    IfcCartesianPoint element = new IfcCartesianPoint(inputLine);
}

public void convertIfcDirection(string inputLine)
{
    IfcDirection element = new IfcDirection(inputLine);
}

Concretely I would like to do something like that :

public void ConvertString(string ClassName,string inputLine)
{
    ClassName element = new ClassName(inputLine);
}

So I just would launch the function like that :

this.ConvertToString("IfcCartesianPoint",inputLine);
this.ConvertToString("IfcDirection",inputLine);
Siegfried.V
  • 1,508
  • 1
  • 16
  • 34
  • Using reflection? Then wrap it up in a factory? – CodeCaster Nov 25 '22 at 12:47
  • 1
    @CodeCaster thanks for the key word, at least can look further :) – Siegfried.V Nov 25 '22 at 12:49
  • 1
    `public static void ConvertString(string ClassName, string inputLine) { Type type = Type.GetType(ClassName); object instance = Activator.CreateInstance(type, inputLine); }` – Vivek Nuna Nov 25 '22 at 12:55
  • @vivek thanks, in fact the question was directly closed, and the link doesn't fully answer to my question. How am I supposed to launch a function? I mean, as I don't know the type in advance, I cannot do something like `type element=new type(inputLine)`? (didn't understand the `Activator.CreateInstance(type, inputLine);` part) – Siegfried.V Nov 25 '22 at 13:15
  • @viveknuna just noticed you made the function static, it has an importance I guess? – Siegfried.V Nov 25 '22 at 13:16
  • @Siegfried.V you can remove the `static` if it's not required. – Vivek Nuna Nov 25 '22 at 13:18
  • @vivek thanks, in fact I see no compilation error anymore, will test that, thanks. And what if the object doesn't have such a constructor `IfcElement(string line)`, this will throw an exception? – Siegfried.V Nov 25 '22 at 13:20
  • @Siegfried.V can you raise a new question for this and you can mention your new requirement in that and share the link – Vivek Nuna Nov 25 '22 at 13:23
  • 1
    @viveknuna no problem, first will test your answer, then will post if I couldn't find a solution, then share U the link – Siegfried.V Nov 25 '22 at 13:31
  • @viveknuna here is the link, thanks https://stackoverflow.com/questions/74573876/error-using-reflexion-when-trying-to-get-the-type – Siegfried.V Nov 25 '22 at 13:55

0 Answers0