Inheriting Static/Shared Fields and Properties

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I'm x-training to .NET at the moment from Java. I have a question regarding
how to implement in .NET the following Java feature.

In Java interfaces it is possible to define static final fields (and assign
values to them) - these fields provide constants that can be exploited by all
classes implementing those interfaces.

Thus inheritance is used to provide static constants with wide (but
definable) scope.

In .NET i've found this is not directly possible ... (tho. feel free to
correct me on this)

Alternatives are just create a class with the constants (but then all
classes and client programmers can access them - maybe this is undesirable)
or create a class containing the constants - messy and can potentially run
into problems through mutiple inheritance (I want to extend X but would also
like to inherit the constants in Y)

I know .NET interfaces allow the signature of properties to be defined in
Interfaces, but assignation of a value to a Shared member in an interface
appears to be forbbiden.

I have found the above Java feature very useful, and would like to re-use
this approach if possible.


Thanks in advance for help.
 
Hi Craig,
In Java interfaces it is possible to define static final fields (and assign
values to them) - these fields provide constants that can be exploited by all
classes implementing those interfaces.

Thus inheritance is used to provide static constants with wide (but
definable) scope.

In .NET i've found this is not directly possible ... (tho. feel free to
correct me on this)

Alternatives are just create a class with the constants (but then all
classes and client programmers can access them - maybe this is undesirable)
or create a class containing the constants - messy and can potentially run
into problems through mutiple inheritance (I want to extend X but would also
like to inherit the constants in Y)

in Java these interface are mostly used like enums in C#/.NET.
You may try this pattern, if your consts are of integral type:

// the value doesn't care at all
public enum SomeName {
Foo,
Bar
}

or

// you need a special value, i.e. to pass them
// to an unmanaged resource, etc.
public enum SomeName {
Foo = 17,
Bar = 1
}

or

// values can be combined with the OR operator
[Flags]
public enum SomeName {
Read = 0,
Write = 2,
Execute = 4
}


if you need to deal with several type:

public sealed class Foo {
public const string Bar = "whatever";
public const int SomeInt = 1;
....

private Foo() {
// prohibit instances
}
}

bye
rob
 
Back
Top