# Solved: initialize base class constructor from derived class in C#



## vikkyhacks (May 12, 2012)

using System;
class A
{
public A(int a)
{
Console.WriteLine(a);
}
}
class B:A
{
public B(int b):base(1)
{
Console.WriteLine(b);
}
}
class MAIN 
{
public static void Main()
{
B b_class = new B(2);
}
}

OUTPUT:
1
2

... this is fine, but i want to initialize class A constructor with the same variable which was passed inside B
ie I want it like this

class B:A
{
public B(int b) 
{
* base(b);*
Console.WriteLine(b);
}
}

but this does not work 
any way to initialize both class A and class B constructors with same values


----------



## Aftab (Oct 15, 2003)

Replace 
public B(int b):base(1) 
with public B(int b):base(b)


----------



## vikkyhacks (May 12, 2012)

hmmm, ... that seems like it will work for one variable but how do i get if for two difference variables like

public B(int b):base(int a) 

.... now I know that the one above will flash me an error ...


----------



## Aftab (Oct 15, 2003)

Hi,

I'm not entirely sure what you're asking. If you're asking whether you can call the base class constructor at any point in the derived class constructor, thereby enabling you to pass any member variable from derived class' constructor as param, then that's not possible. If you're asking whether you can choose what to pass to the base constructor, then yes.

This is not allowed:

class B:A
{
public B(int b) 
{
int c;
* base(c);* can't call cstr here
}
}

This is allowed (assuming the base class has a constructor which takes 2 int params).
public B(int a, int b, int c) : base( b, 100)
{
Console.WriteLine(b);
}


----------



## vikkyhacks (May 12, 2012)

hey I got it .. !!!

```
using System;
class A
{
    public A(string a) {Console.WriteLine(a);}
}
class B:A
{
    public B(string b,string a):base(a) { Console.WriteLine(b); }
}
class MAIN
{
    public static void Main()
    {
      B classB =  new B("class b","class a");
    }
}
```
got an idea when i looked at your code !!! thanks ...


----------

