I have the following code:
struct test {
public int a;
public int b;
public test(int a) {
this(a, null);
}
public test(int a, int b) {
this.a = a;
this.b = b;
}
}
Where I would like to have two different constructors for the test struct, one where I only need to pass in a and another where I can pass in both a and b.
This code does not work, as it fails with a few errors:
For the public test(int a) { line:
Field 'test.a' must be fully assigned before control is returned to the caller
Field 'test.b' must be fully assigned before control is returned to the caller
And for the this(a, null); line:
Method name expected.
The 'this' object cannot be used before all of its fields have been assigned
struct test {
public int a;
public int b;
public test(int a) : this(a, 0) { }
public test(int a, int b = 0) {
this.a = a;
this.b = b;
}
}
You can't assign null to int. Also your variable names are ambiguous. You can use an optional parameter to achieve what you're looking for. Or chaining constructors.
Try this
struct Test
{
public readonly int a;
public readonly int b;
public Test(int a) : this()
{
this.a = a;
this.b = 0;
}
public Test(int a, int b) : this()
{
this.a = a;
this.b = b;
}
}
an alternative is to use an optional parameter with one constructor
public Test(int a, int b = 0) : this()
{
this.a = a;
this.b = b;
}
or instead of 0 to use default(int), or just default
public Test(int a) : this()
{
this.a = a;
this.b = default(int);
}
The : this() call is added by Microsoft when the create constructor tool is used so I have added it here. I think it is just to remind the reader of the code that space in the stack is allocated first and then the fields are assigned.
I also added the readonly keyword because mutable structures are evil and to emphasize the requirements the fields need to be all defined before the constructor ends.
Or you can always use one constructor from another constructor
public Test(int a) : this(a, 0)
{ }
Related
class parent
public string a;
public string b;
// child fields
public string c;
public string d;
public parent(string a, string b)
{
this.a = a;
this.b = b;
}
class child1 : parent
{
public child1(string a, string b, string c) :base(string a, string b)
}
class child2 : parent
{
public child2(string a, string b, string d) :base(string a, string b)
}
IList<parent> parent_list = new List<parent>();
parent_list.Add(new child1("243", "ewfwe", "fewf"));
parent_list.Add(new child2("456", "fewf", "efew"));
parent_list.Add(new child1("123", "efe", "ewfew"));
parent_list.Add(new child2("768", "fewf", "ewf"));
var foo = 123
I want to delete all data for an object which has 123 as their field a.
I cant seem to find the correct way to execute this. is it possible?
Yes, you can apply this code.
parent_list = parent_list.Where(item => item.a != "123").ToList();
More details on Where
Just count backwards through the list, removing items as you go:
for(var i = parent_list.Count - 1; i >= 0; i--)
if(parent_list[i].a == "123")
parent_list.Remove(i);
The following code initializes the base class from derived class using 'base' keyword by calling the base class constructor from the derived class.
class A
{
public int a;
public int b;
public A(int x, int y)
{
a = x;
b = y;
}
}
class B : A
{
int c;
public B(int s, int n,int z)
: base(s, n)
{
c = z;
}
public int add()
{
return a + b+c;
}
}
class Program
{
static void Main(string[] args)
{
B b = new B(2, 3,5);
Console.WriteLine(b.add());//the output is 10 OK
}
}
Question
what happens if a derived class inherits from more than one base class.then how to initialize all the base classes from the derived class using base keyword(how to call the base class constructors).**
class A
{
public int a;
public int b;
public A(int x, int y)
{
a = x;
b = y;
}
}
class B:A
{
public int d;
public int e;
public B(int x, int y)
{
d = x;
e = y;
}
}
class C:B
{
}
then from class C how to initialize both the base classes using base keyword.
A class can only inherit from one base class.
If your base class inherits from some other base class, your base class will initialize its base class, just like any other class.
As others have said, in .Net you can only inherit from one Class, however you can implement a large number of interfaces. The difference and how to achieve an effect similar to inheriting from a number of classes is out of scope of this question.
In your example (using the previous code sample as a standard) you would have to do the following
class A
{
public int a;
public int b;
public A(int x, int y)
{
a = x;
b = y;
}
}
class B:A
{
public int d;
public int e;
public B(int x, int y): base (x, y)
{
d = x;
e = y;
}
}
class C:B
{
public C(int m, int n) : base(m, n)
}
This would in effect instantiate C, which then calls the constructor of B which then calls the constructor of A.
Inheriting from multiple classes is not allowed in .Net. (Cause that would lead to Diamond problem). But implementing from multiple interface and multi level inheritance is allowed.
In first snippet first A's constructor is called followed by B's constructor.
In second snippet first A's constructor will be called, then B's followed by C's constructor.
You can try this out like so in LINQPad:
Copy-pastable code below (note, will only be 'valid' in LinqPad, due to } in odd places - requirement of linqpad)
var test = new C(1, 2);
}
class A
{
public int a;
public int b;
public A(int x, int y)
{
a = x;
b = y;
Console.WriteLine("A");
}
}
class B : A
{
public int d;
public int e;
public B(int x, int y) : base(x, y)
{
d = x;
e = y;
Console.WriteLine("B");
}
}
class C : B
{
public C(int x, int y) : base(x, y)
{
Console.WriteLine("C");
}
I have two interfaces A,B both has same method declarations. I have a class C inheriting from interfaces A,B. I have another class D inheriting from C. Now i want to access the implemented methods in C from D
interface A
{
int add(int x, int y);
int mul(int x, int y);
}
interface B
{
int add(int x, int y);
int mul(int x, int y);
}
public class C : A,B
{
int A.add(int x,int y)
{
return x + y;
}
int A.mul(int x,int y)
{
return 0;
}
int B.add(int x, int y)
{
return x;
}
int B.mul(int x, int y)
{
return y;
}
}
class D : C
{
}
How to access the methods in C from D?
How to access the methods in C from D?
You have to use a reference with a compile-time of the relevant interface. For example:
class D
{
public void FooA()
{
A a = this;
Console.WriteLine(a.mul(...));
}
public void FooB()
{
B b = this;
Console.WriteLine(b.mul(...));
}
}
Of course you don't need the local variable - you can cast:
Console.WriteLine(((A) this).mul(...));
... but it gets a bit ugly.
This is just because you're using explicit interface implementation. If you implemented one of the interfaces implicitly, you could just call the methods directly as normal... but explicit interface implementation only allows a member to be called via that interface.
An explicit interface method invocation should always work
((A)this).mul(1,1);
You can use this code because you have to specify the interface from which you want to use the method (A or B):
((A)this).add(1, 1);
As others already suggested casting is of course one way of doing this. It's quick and simple but if you're going to use it a lot it's annoying. The way out in this case are properties that give access to the members provided by the interface and that conveniently group them thus simplifying their usage:
Easy access without additional casting (you do it only once inside the property getters - see below the C-class):
class Program
{
static void Main(string[] args)
{
C c = new C();
c.As.add(1, 2);
}
}
Interfaces:
public interface A
{
int add(int x, int y);
int mul(int x, int y);
}
public interface B
{
int add(int x, int y);
int mul(int x, int y);
}
C-class:
public class C : A, B
{
// Methods from the A-interface.
public A As { get { return (A)this; } }
// Methods from the B-interface.
public B Bs { get { return (B)this; } }
int A.add(int x, int y)
{
return x + y;
}
int A.mul(int x, int y)
{
return 0;
}
int B.add(int x, int y)
{
return x;
}
int B.mul(int x, int y)
{
return y;
}
}
D-class:
public class D : C
{
public D()
{
base.As.add(1, 2);
base.Bs.add(3, 4);
}
}
Can you check this,
using System;
public class Program
{
public static void Main()
{
D ds=new D(10,12);
int valueAddtion=((A)ds).add(20,122);
int valueMultiplication=((B)ds).mul(20,11);
Console.WriteLine("Mainapplicatin Value of A= " +valueAddtion+" multiplication value= "+valueMultiplication);
}
}
// your code segment here
class D : C
{
public D()
{
int valueAdd=((A)this).add(10,11);
int valueMul=((B)this).mul(20,11);
Console.WriteLine("Addition Value of A= " +valueAdd+" multiplication value= "+valueMul);
}
public D(int x,int y):this()
{
int valueAdd=((A)this).add(x,y);
int valueMul=((B)this).mul(x,y);
Console.WriteLine("Paremeterized Value of A= " +valueAdd+" multiplication value= "+valueMul);
}
}
Output will be,
Addition Value of A= 21 multiplication value= 11
Paremeterized Value of A= 22 multiplication value= 12
Mainapplicatin Value of A= 142 multiplication value= 11
I'm new in .net and C# and I'm trying to create an instance of MyStruct, without known the Type before.
so my class receive 3 type in the constructor and I need to create an Instance of MyStruct with this type.
I looked on internet and saw the last part but I can't compile this.
namespace IQUnionTag
{
public class IQUnionTag
{
private struct MyStruct<A, B, C>
{
public A value1;
public B value2;
public C value3;
}
private object MyStructure;
private Type a;
private Type b;
private Type c;
public IQUnionTag(Type a, Type b, Type c)
{
this.a = a;
this.b = b;
this.c = c;
int d = 2;
var d1 = typeof (MyStruct<>); // Doesn't compile
Type[] typeArgs = { a, b, c };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Console.WriteLine(o);
}
}
}
I just want something like
Mystructure = new MyStruct<a,b,c> // this doesn't compile too
typeof(MyStruct<>) make error compile like
Erreur Using the generic type 'IQUnionTag.IQUnionTag.MyStruct<A,B,C>' requires 3 type arguments
i certainly missed something, can you help me to create my instance?
It is not clear what is your purpose but you can do:
public class IQUnionTag
{
private struct MyStruct<A, B, C>
{
public A value1;
public B value2;
public C value3;
}
private object MyStructure;
private Type a;
private Type b;
private Type c;
public IQUnionTag(Type a, Type b, Type c)
{
this.a = a;
this.b = b;
this.c = c;
int d = 2;
var d1 = typeof(MyStruct<,,>); // this is the way to get type of MyStruct
Type[] typeArgs = { a, b, c };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Console.WriteLine(o);
}
}
I have a class with 2 constructors:
public class Lens
{
public Lens(string parameter1)
{
//blabla
}
public Lens(string parameter1, string parameter2)
{
// want to call constructor with 1 param here..
}
}
I want to call the first constructor from the 2nd one. Is this possible in C#?
Append :this(required params) at the end of the constructor to do 'constructor chaining'
public Test( bool a, int b, string c )
: this( a, b )
{
this.m_C = c;
}
public Test( bool a, int b, float d )
: this( a, b )
{
this.m_D = d;
}
private Test( bool a, int b )
{
this.m_A = a;
this.m_B = b;
}
Source Courtesy of csharp411.com
Yes, you'd use the following
public class Lens
{
public Lens(string parameter1)
{
//blabla
}
public Lens(string parameter1, string parameter2) : this(parameter1)
{
}
}
The order of constructor evaluation must also be taken into consideration when chaining constructors:
To borrow from Gishu's answer, a bit (to keep code somewhat similar):
public Test(bool a, int b, string c)
: this(a, b)
{
this.C = c;
}
private Test(bool a, int b)
{
this.A = a;
this.B = b;
}
If we change the evalution performed in the private constructor, slightly, we will see why constructor ordering is important:
private Test(bool a, int b)
{
// ... remember that this is called by the public constructor
// with `this(...`
if (hasValue(this.C))
{
// ...
}
this.A = a;
this.B = b;
}
Above, I have added a bogus function call that determines whether property C has a value. At first glance, it might seem that C would have a value -- it is set in the calling constructor; however, it is important to remember that constructors are functions.
this(a, b) is called - and must "return" - before the public constructor's body is performed. Stated differently, the last constructor called is the first constructor evaluated. In this case, private is evaluated before public (just to use the visibility as the identifier).