Can I return class object from function in c# as a return value instead return string or int or ..etc
3 Answers
A class object in C# is a Type. So you can definitely return it from a function:
public Type Foo() {
return typeof(string);
}
public Type Bar() {
return someNonNullVariable.GetType();
}
2 Comments
I'm assuming that you want to return a instance of a class from the function, then the answer is yes. An instance of a class is nothing more than an object like basically everything else in .NET.
Example:
public class MeaningfulClassName
{
public int Val1;
public string Val2;
....
}
public class Processor
{
public MeaningfulClassName MyFunction(int something, string somethingelse)
{
var ret = new MeaningfulClassName();
....
return ret;
}
}
1 Comment
I read your question as if a method can return a class. I would, presently, dare say No. Presently is 2018-04-05
Below I am using System.Class, a class most famous for System.Class.WriteLine.
One can not declare
Func<System.Class> C => System.Class;
to be able to
C.WriteLine("Hello world!");
Someone Please prove me Wrong!
I would really love the functionality as it would help med mock a static.
object(System.Object)?