9

I always used to consider structures as some sort of lesser privileged things, or something with lesser features. Maybe because of the OOP concepts blowing everything into Classes.

From the little amount of exposure to C#, I understand that Setting a class static, ensures that all its members & functions are static. Also we cannot have a constructor to initialize that class as there is only a single instance.

public static struct mystruct
{
    public static int a;
}

I was pointed out right here at Stack overflow that this is a wrong method. Can someone elaborate.

I got the appropriate error saying "static is not valid for this item" when I created a new cs file & compiled it in console. Strangely when I added this to an existing working project to see if the compiler would complain but to my surprise it doesn't. Any reasons for this??

loxxy
  • 12,990
  • 2
  • 25
  • 56
  • 6
    In C#, `static` is an alias for `abstract sealed` on a type declaration (it also allows some other compile-time checks such as making sure methods are static too). Since structs are value types and do not allow polymorphic behavior, then it makes sense why `static` isn't allowed. You can however, have static members on a struct. – Steve Guidi Sep 16 '10 at 20:00
  • 2
    @Steve: If the class is static, the compiler also checks the *use* of the type name. For example, you can't declare a parameter of type Enumerable. You may well have been aware of that, but I wanted to draw attention to it :) – Jon Skeet Sep 16 '10 at 20:40
  • @Jon: That's right -- thank you for reminding me of that. – Steve Guidi Sep 16 '10 at 21:18

7 Answers7

17

A static class is just a container for static members (of any kind - fields, events, properties, and most commonly methods).

A static struct would be exactly the same, so wouldn't provide any advantages - but readers might think it had some special meaning. To avoid confusion, it's therefore prohibited. Conceptually it makes just as much sense as a static class, of course - the difference between structs and classes is really in terms of how instances of them behave, and as there would be no instances of static types of either kind, that difference would be moot.

(Not that I was in the design meeting where this was decided, of course. Eric Lippert may well be able to find some notes about it. The above is just an educated guess. The annotated C# 3 spec is silent on the matter, as far as I can see.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    You mean you were *not* in the design meeting? – Dan Tao Sep 16 '10 at 19:56
  • 1
    @Dan: Alas, I've never been in any C# design meetings. I would *love* to be, of course. – Jon Skeet Sep 16 '10 at 19:58
  • @Jon: Sorry, I just read the sentence wrong the first time. Personally, I think I would *hate* to be at such a meeting... too much pressure to make smart decisions! – Dan Tao Sep 16 '10 at 20:04
  • 3
    Makes sense to me. :-) Personally I think it would have been even better to go the VB route and make yet a third thing, a "module", say, that would be just like a static class. A container of static methods is logically neither a value type nor a reference type, so why fool people into thinking that it is by calling it a kind of 'class'? Had static classes been invented in C# 1.0 I think that would have been the way to go. But since they came along in 2.0 there is pressure there against making a new keyword "module", or whatever it would be. "static" and "class" were already reserved. – Eric Lippert Sep 16 '10 at 23:55
  • 1
    They held C# design meetings? And here I thought the language was the sole work of Anders Hejlsberg. :) – tcrosley Sep 17 '10 at 00:46
  • @Eric: I thought when you guys made a new language, you tried to reserve as many keywords as reasonably possible from the start. Is this not true? – Joan Venge Sep 17 '10 at 16:36
  • 2
    @Joan: Nope. We try to reserve as few keywords as reasonably possible from the start. For example, keywords "get", "set" and "value" are unreserved in every version of C# because the designers figured that programmers would want to use them for variable names. See http://blogs.msdn.com/b/ericlippert/archive/2009/05/11/reserved-and-contextual-keywords.aspx for details. Other companies make different choices; for example, the designers of JavaScript decided to reserve every keyword of Java whether that made sense or not, just in case they'd need them in the future. – Eric Lippert Sep 17 '10 at 18:05
8

This doesn't accomplish anything. You'd still have a collection of static methods just like you do with a static class. A struct in C# implies it is a value type instead of a reference type, which has no meaning at the static level.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
3

File that under "that's just the way it is". Since you can do it with a static class, there is not reason to allow static structs. It would just confuse people as to what the difference between them is. They had to pick one or the other.

Bryan
  • 2,775
  • 3
  • 28
  • 40
3

Also we cannot have a constructor to initialize that class as there is only a single instance.

Actually, there is no instance of a static class. Which kind of explains the lack of support for static structs -- or rather, the lack of any need for such a thing.

The distinction between reference types and value types in .NET (class and struct in C#) is entirely about how instances of these types are handled. An instance of a reference type is accessed via a reference to that instance in the form of a variable. Copies to such references are passed around between method calls. An instance of a value type is accessed directly, and copies of the instance itself are passed around between method calls.

With no instance to speak of, this distinction becomes irrelevant; so any type that consists purely of static members might as well be a static class.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
3

No Instance Field Initializers

In a class we are allowed to create a field/variable and initialize it at the same time A structure cannot contain such initialization. These fields must be initialized through functions or by using the object itself. Fields cannot be given initial values at the time of creation. The following code gives an error:

struct Point
{ 
    public int x = 20; // Error its not possible to initialize
    public int y=20; // Error its not possible to initialize
} 

However a struct can contain static fields, which can be initialized inside the struct. The following example shows the use of static fields inside a struct.

struct  Point  {
        public static int x = 25;
        public static int y = 50;
}

Struct & Methods

A C# struct can also contain methods. The methods can be either static or non-static. But static methods can access only other static members and they can't invoke by using an object of the structure. They can invoke only by using the struct name.

struct Point  
{    
    static int x = 25;    
    static int y = 50;
    public void SetXY(int i, int j)    
    {        
        x = i;        
        y = j;    
    }     

    public static void ShowSum()            
    {        
        int sum = x + y;        
        Console.WriteLine("The sum is {0}",sum);    
    }
}

as found on "http://www.csharpfriends.com/articles/getarticle.aspx?articleid=120"

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Michael Eakins
  • 4,149
  • 3
  • 35
  • 54
1

The concept of static types doesn't make sense for structs. Structs imply copy-by-value semantics - which only makes sense when you can instantiate a type. Static classes were introduced to make it easier to group together static methods in a type that can't be instantiated. Allowing static structs would be both redundant and confusing.

Think about it this way. How would static class Foo and static struct Foo differ in behavior? And if they don't ... why introduce a static struct concept at all? It could only confuse people into thinking there is a difference...

LBushkin
  • 129,300
  • 32
  • 216
  • 265
  • I take your point. But surely "class" implies copy-by-reference semantics, ability to create instances, and sharing of implementation details via inheritance, none of which are true of static classes. It's not at all obvious that static class is *better* than static struct, and it's arguably worse. – Eric Lippert Sep 16 '10 at 23:57
  • @Eric: Indeed it does ... and perhaps some third kind of concept (module as you mention in your comment to Jon's post) may have been better. I guess what I was trying to say (poorly) is that having *both* static class and static struct would be confusing and imply a behavioral difference that didn't exist. – LBushkin Sep 17 '10 at 13:47
1

Because static is not defined to be allowed in the language to be applied to structs.

static class already defines the same ability.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636