-3

is there some way how I can this do in C#? I can not use this(int,int) in C# code. Can you write me some similar code which will be in C# and will do the same things? Thank you! :)

public class JavaApplication2
{
    public static class SomeClass 
    {
        private int x;
        private int y;

        public SomeClass () { this(90,90); }
        public SomeClass(int x, int y) { this.x = x; this.y = y; }
        public void ShowMeValues ()
        {
            System.out.print(this.x);
            System.out.print(this.y);
        }
    }
    public static void main(String[] args) 
    {
        SomeClass myclass = new SomeClass ();
        myclass.ShowMeValues();
    }
}
yazanpro
  • 4,512
  • 6
  • 44
  • 66
Facedown
  • 123
  • 1
  • 7
  • if both constructors are public why not using just second one with parameters? Or if you want some default value for `int x` and `int y` - just set it in Class definition as `private int x = 90; ` – Fabio Aug 23 '13 at 18:27
  • for example: http://stackoverflow.com/questions/3146152/c-if-a-class-has-two-constructors-what-is-the-best-way-for-these-constructors – shieldgenerator7 Aug 23 '13 at 18:28
  • possible duplicate of [call one constructor from another](http://stackoverflow.com/questions/4009013/call-one-constructor-from-another) – Rob Kennedy Aug 23 '13 at 18:33

2 Answers2

4

Yes, C# can chain constructors:

public SomeClass() :this(90,90) {}
public SomeClass(int x, int y) { this.x = x; this.y = y; }

This is covered on MSDN in Using Constructors.

That being said, in C#, the class will have to not be static, as well.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

There are several things that need to be changed if you want to translate this to C#:

  1. The main the problem is that you've declared SomeClass as static. It won't compile because static classes cannot have instance members. You need to remove the static keyword.
  2. To invoke a constructor from another you need to use : this(...) after the constructor parameters (or : base(...) to invoke a constructor of the parent class).
  3. Instead of System.out, for .NET applications you need to use System.Console.

This should work for you:

public class SomeClass 
{
    private int x;
    private int y;

    public SomeClass () : this(90,90) { }
    public SomeClass(int x, int y) { this.x = x; this.y = y; }
    public void ShowMeValues ()
    {
        Console.WriteLine(this.x);
        Console.WriteLine(this.y);
    }
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331