C
C#2y ago
voltron__

❔ work many file in C#

I would like to know how to work in several files in C#, example: I create a class in the base.cs file and I would like to use it in my program.cs file. pls help. (i use visual studio code).
3 Replies
FusedQyou
FusedQyou2y ago
If your class is not static, you create a new instance of the class using the new() keyword, and store it in a variable. You can then use it through this variable. If your class is static, you can just use it directly since there is only one instance. Suggest you google how c# works with these things before you make everything static 😉
Pobiega
Pobiega2y ago
Be aware that VS Code is not really recommended for C#, but you can use it if you really want to. That said... C# isn't file based, so the compiler itself is fine with you using one or several files, it hardly cares at all. As Fused said, its very common to make a new file for each class you make
// in "Program.cs"
public static class Program
{
public static void Main()
{
var data1 = GetDataFromProgram();
var data2 = StaticClass.GetDataFromStaticClass();

var normalClassInstance = new NormalClass();
var data3 = normalClassInstance.GetDataFromNormalClass();
}

private static string GetDataFromProgram()
{
return "hello";
}
}

// in "StaticClass.cs"
public static class StaticClass
{
public static string GetDataFromStaticClass()
{
return "hello from a static class!";
}
}

// in "NormalClass.cs"
public class NormalClass
{
public string GetDataFromNormalClass()
{
return "hello from a normal class";
}
}
// in "Program.cs"
public static class Program
{
public static void Main()
{
var data1 = GetDataFromProgram();
var data2 = StaticClass.GetDataFromStaticClass();

var normalClassInstance = new NormalClass();
var data3 = normalClassInstance.GetDataFromNormalClass();
}

private static string GetDataFromProgram()
{
return "hello";
}
}

// in "StaticClass.cs"
public static class StaticClass
{
public static string GetDataFromStaticClass()
{
return "hello from a static class!";
}
}

// in "NormalClass.cs"
public class NormalClass
{
public string GetDataFromNormalClass()
{
return "hello from a normal class";
}
}
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server