user1733537
user1733537

Reputation: 69

Can you use a class inside of a function in C#

I was wondering if I could use a class inside of a function. I would the call the function in another file using using filename.FuntionName(); I made the class public so that it would more likely cooperate. Also, would using filename.FunctionName(); call the function from the other file, or just use it as a resource? Well, here is the code:

namespace file
{
public void file()
{
    public class file
    {
        /*function
        code*/
        }
    }
}       

Upvotes: 2

Views: 5652

Answers (3)

Casperah
Casperah

Reputation: 4564

The correct way to declare a function:

namespace Company.Utilities.File
{
    public class File
    {
        public File(string filename)
        {
           Filename = filename;
        }

        public string Filename { get; private set; }

        public void Process()
        {
            // Some code to process the file.
        }

        public static void ProcessFile(string filename)
        {
            File file = new File(filename);
            file.Process();
        }
    }
}

The point with the long namespace name is that it should be unique even when using assemblies from other companies (Third Part assemblies)

If you want to call the class like it was a function you should create a static function (like ProcessFile) then you can call File.ProcessFile(filename);

Upvotes: 0

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20640

I suspect what you're looking for is a static method.

namespace SomeNamespace
{
    public class SomeClass
    {
        public static void CallMe()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Then you can call SomeNameSpace.SomeClass.CallMe() from elsewhere without having to create a new instance of SomeClass.

Upvotes: 2

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

You cant declare classes inside functions like Java , however you can use var to create an anonymous type that are not visible outside the function

  void file()
    {
        var file=new {
            path="path",
            size=200};
        Console.WriteLine(file.path+"  "+file.size);
    }

Upvotes: 2

Related Questions