structs

C# learner

Active member
Joined
Dec 22, 2022
Messages
40
Programming Experience
Beginner
I got a lot of help from coders about my last post and again thank you. Have another question. I tried setting up a struct but it makes all variables in the whole program go red underline. Does it have to be setup in the class that it pertains to? The syntax for struct is
C#:
struct name
{
variables
}
correct?
A little help, please.
 
Last edited by a moderator:
No a struct does not have to be declared within a class. The following works perfectly well:
C#:
struct MinMax
{
    public int Min;
    public int Max;
}

class WeatherReading
{
    public DateTime TimeStamp;
    public MinMax temperature;
}

class Planet
{
    public string Name;
    public MinMax orbit;
}
 
No a struct does not have to be declared within a class.
And nor should it, in the vast majority of cases. Structures should be treated the same way classes are treated, which generally mean declaring them in a dedicated code file with the same name as the type. There's rarely a reason to declare one type inside another, unless the inner type is declared private. I usually declare every type in its own code file but I do break that rule under specific circumstances. Because they are very simple, I generally declare all enums in a single code file named Enumerations.cs. If I have multiple view models in an MVC app that all correspond to the same entity but with slightly different properties, I will often use a single code file too. You could possibly use the same logic for structures.
 
I got a lot of help from coders about my last post and again thank you. Have another question. I tried setting up a struct but it makes all variables in the whole program go red underline. Does it have to be setup in the class that it pertains to? The syntax for struct is
C#:
struct name
{
variables
}
correct?
A little help, please.
If you wrote it exactly like that then of course it didn't work, because the part between the braces is not valid C# code. If you didn't do it exactly like that then we can only guess at what you did wrong because we don't know what you actually did.
 
I'm guessing it is because I suggested using struct in his other thread to contain the tuple that he was trying to return. Since the modern implementation of the tuple in C# is a ValueTuple replacing the previous Tuple. The former is a struct while the latter is a class.
 
Back
Top Bottom