Question

I am facing a problem in my C# code. I would like to convert a variable of type T to a string, using the toString() method. I have overridden this method for my own types, and it is important for the variable I use to be generic, because it can take values of multiple types. I have tried using a cast to Object, but it returns an error saying that

 'object' does not contain a definition for 'toString' and no extension method 'toString' accepting a first argument of type 'object' could be found.

This is the line of code:

 T stud;
 students += (stud as Object).toString()+"\n";
Was it helpful?

Solution 2

It is ToString(); C# is case sensitive. Also, as already explained in the comments, you don't need to use the as Object conversione because every class in C# has the ToString() method defined because every class derive from object

However, if the code above is exactly your code, you have another problem.

The variable stud of type T is not initialized anywhere and using

(stud as Object).ToString()

will result in a null reference exception

OTHER TIPS

This is because System.Object defines method ToString with the capital T. Change the case to fix the problem.

Note: the code that concatenates strings with += is often inefficient. If you need to concatenate a small, fixed, number of strings, use string.Format("{0}\n{2}", firstString, secondString). If you need to concatenate a larger number of strings, use a StringBuilder, or a string.Join method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top