7

Can I return class object from function in c# as a return value instead return string or int or ..etc

1
  • 3
    Your question isn't clear. Do you want a function that returns a class (i.e., a type, not an instance), or do you want a function that returns type object (System.Object)? Commented Nov 16, 2010 at 4:23

3 Answers 3

13

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

ok what is the wrong in this function public Bill_spec Get_Bill_Items(string getbillnum, Bill_spec current_bill) { return current_bill;}
You're returning an instance of Bill_spec, not a class object. (I'm ignoring the fact that you're simply returning one of the parameters, which makes for an odd function.)
8

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 needed to return a class based on a string variable. All the examples I found used Type and typeof which have slightly different things accessible to the object. This is the first and only solution I found that brings back the class that I can use, thanks!
-2

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.