Page 1 of 1

Static Class in Cobra?

PostPosted: Sun May 29, 2011 10:00 am
by carlosqt
Hi there,

(environment: windows 7 64 bit (but using .net 32 bit) - using "Cobra 2010-10-18" modified to use .NET 4.0 using ildasm-ilasm (option 4 by RIGHT_THEN)

I think this topic has been already discussed, but didn't really find a simple YES/NO answer.

Is it possible to declare a class shared with all its members shared as well?

The code below declares an instance class with only shared members and correctly compiles:
use System

class Greet
var name as String is shared
cue init is shared
#base.init
.name = "carlos"
def salute is shared
print "Hello [.name]!"

# Greet the world!
class GreetProgram
def main is shared
pass


if I add "is shared" to the class to make it a pure static class then I get a compile error
use System

class Greet is shared
var name as String is shared
cue init is shared
.name = "carlos"
def salute is shared
print "Hello [.name]!"

# Greet the world!
class GreetProgram
def main is shared
pass


The error is:
C:\Cobra\bin40>cobra.exe test2.cobra -ref:System.Numerics.dll
c:\Cobra\bin40\test2.cobra(4): error: "Greet._ih_invariantGuard" : impossible de
déclarer les membres d"instance dans une classe static
Compilation failed - 1 error, 0 warnings
Not running due to errors above.

(impossible to declare instance members on an static class)

Thanks in advance.

Re: Static Class in Cobra?

PostPosted: Sun May 29, 2011 10:52 am
by Charles
Cobra doesn't support that at this time. You might be interested to know that you can do this:
class Greet
shared # make all members underneath this shared
var name as String
cue init
.name = "carlos"
def salute is shared
print "Hello [.name]!"


I hardly use shared methods myself. One difficulty with them is that they cannot be overridden in subclasses. Also the more shared methods you have, the more shared variables tend to accumulate. These are effectively global variables and you end up with the usual problems. With objects, it's easier to confine state, to throw objects away in favor of new ones, to cache them in collections, etc. Using 'shared' eliminates all of that.

But if you still want 'shared' you can have it as seen above.

Btw you can skip "use System" if you like--it's automatic.

Also, in these forums, you can use (cobra) (/cobra) tags instead of (code) (/code) to get syntax highlighting (obviously use square brackets when using those tags for real).

HTH.

Re: Static Class in Cobra?

PostPosted: Sun May 29, 2011 11:14 am
by carlosqt
Thanks a lot for the quick answer.

So, using shared instead of is shared will do the trick. Excellent.

The purpose of the little program I'm building is to show what features are available between several languages, including static/shared class which in other languages is not supported (jscript.net, phalanger) or are called modules (VB.NET, F#, Nemerle), and so on.

So, good that I asked and that it is supported before I said it was not :D

Bytes!