Home > Software engineering >  Import class from another folder
Import class from another folder

Time:09-29

I'm pretty new to the whole C# thing and I'm a bit used to C with the header files. So I hope this isn't the dumbest question.

How can I import the MainWindow.cs into the MainWindow.xaml.cs? I thought I could just use using MainWindow.cs

This is the project structure

CodePudding user response:

In .Net you can use any class in the same project, or in any referenced project or dll. You never need to worry about header files. The .Net assemblies themselves contain all the type information needed to use them.

Type disambiguation is done with namespaces, you should typically place types in a namespace like ProjectName.Folder I.e.

namespace MyProject.Quelldateien.Inc{
    public class MainWindow{
        ...
    }
}

In your code file you need to use the full namespace when refering to a type, i.e. MyProject.Quelldateien.Inc.MainWindow, or add a using statement at the top of your file:

using MyProject.Quelldateien.Inc
namespace MyProject{
    public class MyClass{ 
    ...
    }
}

Note that you should usually try to avoid using the same name for classes, since this would require using the full namespace to refer to your type. A common convention is for your name your xaml-classes MyMainView and the view model class (containing properties you bind to) as MyMainViewModel. And place this in separate folders.

Also note that some refactoring tools can add namespaces automatically, so I almost never write out using MyProject.Quelldateien.Inc, I just write my type name, and accept the namespace suggestion by the tool.

CodePudding user response:

in the MainWindow.cs see the namespace. like:

namespace Quelldateien.inc
{
    internal class MainWindow
    {
    }
}

then use:

using Quelldateien.inc;
  •  Tags:  
  • c#
  • Related