Home > Back-end >  Custom class shares name with C# class
Custom class shares name with C# class

Time:09-28

I am looking through the codebase left behind by my predecessor and got confused by the following class definition, which appears to copy a Microsoft defined class:

//...
using System.Diagnostics;

namespace Processes;
public class Process
{
    public Process(ProcessType processType, ILogger log)
    {
        this.ProcessType = processType;
        this.StopWatch = Stopwatch.StartNew();
        this.PopulateProcessors();

        Log.Process = this;
        Log.Logger = log;
    }
//...
}

The files goes on for awhile and includes a definition for a method called Start(), amongst others. I'm confused because Microsoft already defines a Process class, with a Start() method, in the System.Diagnostics namespace, which is being used here.

So how can we be defining a class that already exists, and is not being inherited? There's clearly a gap in my knowledge. What am I missing here?

CodePudding user response:

You can have multiple classes with the same name, as long as they have different namespaces. For example:

System.Threading.Timer;
System.Windows.Forms.Timer;

These namespaces both have a class called Timer. This would normally cause ambiguity, but you can use both of them by doing this:

using ThreadingTimer = System.Threading.Timer;
using FormsTimer = System.Windows.Forms.Timer;

void StartFormsTimer()
{
    FormsTimer myFormsTimer = new FormsTimer();
    myFormsTimer.Interval = 1000;
    myFormsTimer.Start();
}

Or, you can add the namespace every time you use Timer:

System.Threading.Timer threadingTimer = new System.Threading.Timer();
System.Windows.Forms.Timer formsTimer = new System.Windows.Forms.Timer();

It's a matter of personal preference. I generally try to avoid having multiple classes with the same name to avoid confusion.

  • Related