Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# have an equivalent of Java static nested class?

Tags:

I am converting Java into C# and have the following code (see discussion in Java Context about its use). One approach might be to create a separate file/class but is there a C# idom which preserves the intention in the Java code?

   public class Foo {

    // Foo fields and functions
    // ...
        private static class SGroup {
            private static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>();

            public SGroup(int id, String type) {
    // ...
            }
        }
    }
like image 899
peter.murray.rust Avatar asked Oct 17 '09 11:10

peter.murray.rust


People also ask

Does C have do-while?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .


2 Answers

All C# nested classes are like Java static nested classes:

C#:

class Outer
{
    class Inner
    {
    }
}

Is like Java's:

class Outer
{
    static class Inner
    {
    }
}

In other words, an instance of Inner doesn't have an implicit reference to an instance of Outer.

There isn't the equivalent of a Java inner class in C# though.

The accessibility rules are somewhat different between the two languages though: in C#, the code in the nested class has access to private members in the containing class; in Java all code declared within one top-level type has access to all the other private members declared within that same top-level type.

like image 104
Jon Skeet Avatar answered Oct 09 '22 10:10

Jon Skeet


Give this a look http://blogs.msdn.com/oldnewthing/archive/2006/08/01/685248.aspx

I am looking specifically at

In other words, Java inner classes are syntactic sugar that is not available to C#. In C#, you have to do it manually.

If you want, you can create your own sugar:

class OuterClass {
 ...
 InnerClass NewInnerClass() {
  return new InnerClass(this);
 }
 void SomeFunction() {
  InnerClass i = this.NewInnerClass();
  i.GetOuterString();
 }
}

Where you would want to write in Java new o.InnerClass(...) you can write in C# either o.NewInnerClass(...) or new InnerClass(o, ...). Yes, it's just a bunch of moving the word new around. Like I said, it's just sugar.

like image 42
Maestro1024 Avatar answered Oct 09 '22 10:10

Maestro1024