Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom class shares name with C# class

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading