Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fields not allowed in C# interface

Tags:

java

c#

There are quite a lot of deviations in Java and C# languages, one of which I observed was we cannot add variable constants in an interface. Being from Java background I got baffled to see compilation error when I tried this.

Does anyone has explanation why it is so?

like image 308
Ravisha Avatar asked Feb 01 '10 09:02

Ravisha


People also ask

Is array of bit fields allowed?

If the value is zero, the declaration has no declarator . Arrays of bit fields, pointers to bit fields, and functions returning bit fields are not allowed. The optional declarator names the bit field. Bit fields can only be declared as part of a structure.

What are bit fields in C?

Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.

Can bit fields be used in Union?

Bit fields CANNOT be used in union.

Can bit fields only be declared as part of a structure?

Bit fields can only be declared as part of a structure.


1 Answers

A field is an implementation detail of a class and should not be exposed an its interface. An interface is a way to abstract away implementation details of a class. These two concepts look contradictory and don't really fit together.

You can declare properties in interfaces instead.


UPDATE (after realizing the question was about constants, not variable fields): I think (purely my personal speculation) that Java decided to allow such a construct because it didn't have enum types back then. C# has had enums since the beginning and preferred those to constants most of the time. Moreover, you can create a static class in C# and add everything you like in it and ship it along the interface without any real hassles. Supporting such a construct would just make interface definitions more complicated.

like image 165
mmx Avatar answered Sep 22 '22 23:09

mmx