satish kumar V satish kumar V - 3 months ago 10
C# Question

How to save object as string in c#

I have an object of student

Class Student
{
public Student()
{
name = "xyz";
roll = 20;
age = 16;
}
string name;
int roll;
int age;
}

Class Service
{
Student student = new Student();
string s = ???
// what I have to do for getting string like {"name" : "xyz", "roll" : 20, "age" :16}
}


I need the string from the above object.

If i serialize the object I am getting something with escape sequences.

Any help would be greatly appreciable.

Answer

Just use toString();

string s = stuident.toString();

Add an overload to toString() in the class to get pretty print. My personal preferece is to output JSON.

Class Student
{
  public Student()
  {
     name = "xyz";
     roll = 20;
     age = 16;
  }


  public override string toString(){
     return "{name: " + name + ", roll: " + roll + ", age: " + age + "}";
  }

  string name;
  int roll;
  int age;
}
Comments