I have a class
class TestFixture
{
public string a { get; set; }
public int b { get; set; }
public int c { get; set; }
public string d { get; set; }
public string e { get ; set ; }
public int f { get; set; }
public int g { get; set; }
public bool h { get; set; }
public string i { get; set; }
public bool j { get; set; }
public bool k { get; set; }
public TestFixture()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
}
I want to define new TestFixture as SO
new TestFixture { a = "", b = 1, c=2, d="" };
while the rest of properties should be auto defined as it written in constructor.
Is it possible ?
Yes, this is possible. Using an object initializer does not skip calling the constructor.
TestFixture fixture = new TestFixture() // or just new TestFixture { ... }
{
a = "",
b = 1,
c = 2,
d = ""
};
This will call the constructor you've defined and then set a, b, c, and d in your object initializer.
Pop a breakpoint in your constructor and run your debugger. This is should show you how and when things in your code are called.
Debugging in Visual Studio
Refactored:
public class TestFixture
{
public string a { get; set; }
public int b { get; set; }
public int c { get; set; }
public string d { get; set; }
// dosomething should check for null strings
public string e { get { return dosomething(a, b); } }
public int f { get; set; }
public int g { get; set; }
public bool h
{
get { return TestName.Equals("1") && b.Equals("2") ? 1000 : 1; }
}
public string i { get; set; }
public bool j { get { return a != null && a.Equals("FOT"); } }
public bool k { get; set; }
public TestFixture(string a, int b, int c, string d)
: this()
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public TestFixture()
{
f = false;
g = DateTime.Now.ToString("yyMMddhhmmss");
i = 10000000;
k = false;
}
}
#hunter's answer is correct, you can use object initializer syntax, and those properties will be set after your constructor runs. However, I'd like to point out some flaws you may have with your code
public TestFixture()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
This code does not set a or b, but you have things that depend on their values (e, g, j). Object initializer syntax is not going to be useful here, you have to have proper defaults for these values if other values in the constructor will depend upon them.
As an example, when you write var obj = new Bar() { A = "foo" };, that will expand to
var obj = new Bar(); // constructor runs
obj.A = "Foo"; // a is set
Clearly, the code in the constructor that looks at A will not see the value "Foo". If you need it to see this value, object initialization strategy is not going to help. You need a constructor overload that takes the value to be stored in A.
var obj = new Bar("Foo");
If I understand you right, you would like to the a, b, c and d properties to be initialized with the given values before the constructor runs. Unfortunately, that is not possible this way, because the default constructor always runs before the object intializers.
I advise you to do something like this instead:
class TestFixture
{
//... properties
public TestFixture()
{
this.init();
}
public TestFixture(string a, int b, int c, string d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.init();
}
private void init()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
}
This way you can init the a, b, c and d properties before the other initializer code runs.
Related
I have code like this:
class First
{
public int a { get; set; }
public int b { get; set; }
public int c = 2;
public _second;
public First()
{
_second = new Second(c);
this.a = _second.a;
this.b = _second.b;
}
}
class Second
{
public int a;
public int b;
public Second(int c)
{
if(c == 0)
{
a = 1;
b = 2;
}
else
{
a = -1;
b = -2;
}
}
}
How can I pass a and b from First class into second class and then directly from second class set their values withohut using static as declaration in First class.
I have tried this:
class First
{
public int a;
public int b;
public int c = 2;
public _second;
public First()
{
_second = new Second(a, b, c);
}
}
class Second
{
public Second(int a, int b, int c)
{
if(c == 0)
{
a = 1;
b = 2;
}
else
{
a = -1;
b = -2;
}
}
}
but it is not doing the job.
You can simply add a constructor in the Second class that receives the instance of First and updates the public variables of the instance passed
public class Second
{
public Second(int a, int b, int c)
{
// old constructor if still needed
...
}
public Second(First f)
{
int sign = f.c == 0 ? 1 : -1;
f.a = 1 * sign;
f.b = 2 * sign;
}
}
By the way, I suggest to use properties instead of public fieds.
public class First
{
public int a {get;set;}
public int b {get;set;}
public int c {get;set;} = 2;
public Second _second {get;set;}
public First()
{
_second = new Second(this);
}
}
UPDATE
Looking at your image it is clear what is the source of your problem. You are receiving a Form class instance in your Forma constructor. You need to receive a Main instance like
public Forma(Main form, int modulID)
{
.....
}
The base class Form has no knowledge of methods defined in custom form classes. In alternative you can still receive a Form instance but you need to add something like this
public Forma(Form form, int modulID)
{
Main m = form as Main;
if(m != null)
m.helpWindow = new Help(modulID);
}
.....
}
You can pass the fields as ref meaning that you pass a reference to the field passed as parameter not the value. This means changes to the fields inside the Second constructor will be reflected in the First class
class First
{
public int a;
public int b;
public int c = 2;
public Second _second;
public First()
{
_second = new Second(ref a, ref b, c);
}
}
class Second
{
public Second(ref int a, ref int b, int c)
{
if (c == 0)
{
a = 1;
b = 2;
}
else
{
a = -1;
b = -2;
}
}
}
You can pass by ref to any method not just a constructor. You should read more about this topic, here for example
I accomplished it with Interface.
public interface IClass
{
int a { get; set; }
int b { get; set; }
}
class First : IClass
{
public int a { get; set; }
public int b { get; set; }
public int c = 2;
public _second;
public First()
{
_second = new Second(this, c);
}
}
class Second
{
public Second(IClass ic, int c)
{
if(c == 0)
{
ic.a = 1;
ic.b = 2;
}
else
{
ic.a = -1;
ic.b = -2;
}
}
}
I have a class that I use to describe a XYZ coordinate along with 3 properties.
The class looks like this:
class dwePoint
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as dwePoint);
}
protected bool Equals(dwePoint other)
{ //This doesnt seem to work
if(Prop1== "Keep")
{
return false;
}
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Prop1.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
return hashCode;
}
}
}
Checking the XYZ on the Equals, I can filter out duplicates only based on the actual coordinates, ignoring the properties.
In my code, I use a list, so I call the List.Distinct()
Now there is one thing I cant figure out yet:
It is possible there are 2 points with the same XYZ, but with different properties.
In that case I always want to keep the one with a specific string (for example "Keep") and always remove the one that has some other value.
I was already trying some if statements, without any luck...
How should I handle this ?
What you want is not really possible with Distinct since it uses your Equals as it's only input for equality (as it should), so it has no way to even be aware that there could be a difference between the objects.
I think it would be a better design for you to compose your class using a new class, e.g. Point3D containing your coordinates and your 3 properties. Then you can group by the point, and for everything that has more than one equal point, apply your own logic as to which to keep.
In code:
class Point3D
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
// Equals and get hash code here
}
class dwePoint
{
Point3D Coordinate {get;}
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
// Filter list by applying grouping and your custom logic
points = points.GroupBy(p => p.Coordinate)
.Select(x =>
x.OrderByDescending(p => p.Prop1 == "Keep") // Sort so the element you want to keep is first
.First() // If there is only one element, the ordering will not matter
).ToList();
If you really want, the GroupBy also works with your current class design, since only the coordinates takes part in the Equals.
Your GetHashCode runs into a nullref if Prop1 == null, you should fix that.
And another solution: use Aggregate and Lamda to distinct your list. The Equal() on your class only compares the X,Y and Z - the Aggregate lambda makes sure you keep what you want. Probably put the Aggregate in a extension method or Function.
static void Main()
{
List<dwePoint> points = new List<dwePoint>();
// Testdata
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
for (int z = 0; z < 3; z++)
{
points.Add(new dwePoint { X = x, Y = y, Z = z });
if (x == y && x == z) // and some duplicates to Keep
points.Add(new dwePoint { X = x, Y = y, Z = z, Prop1 = "Keep" });
}
// prefer the ones with "Keep" in Prop1
var distincts = points.Aggregate(new HashSet<dwePoint>(), (acc, p) =>
{
if (acc.Contains(p))
{
var oldP = acc.First(point => point.X == p.X && point.Y == p.Y && point.Z == p.Z);
if (oldP.Prop1 == "Keep")
{
// do nothing - error, second point with "keep"
}
else
{
acc.Remove(oldP);
acc.Add(p); // to use this ones other props later on ....
}
}
else
acc.Add(p);
return acc;
}).ToList();
Console.WriteLine(string.Join(" - ", points));
Console.WriteLine(string.Join(" - ", distincts));
Console.ReadLine();
}
private class dwePoint
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as dwePoint);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
return hashCode;
}
}
public override string ToString() => $"{X}-{Y}-{Z}-{Prop1}-{Prop2}-{Prop3}";
protected bool Equals(dwePoint other)
{
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
}
}
I had the same answer in mind as driis provided..
But, I would like to provide you with another option.
You can write a Distinct on your own as an extension method.
Here is a work around. I wrote a sample code, so that you can understand better.
static class Program
{
static void Main(string[] args)
{
List<Abc> list = new List<Abc>()
{
new Abc()
{
a = 5,
b = 6,
s = "Phew"
},
new Abc()
{
a = 9,
b = 10,
s = "Phew"
},
new Abc()
{
a = 5,
b = 6,
s = "Keep"
},
new Abc()
{
a = 9,
b = 10,
s = "Keep"
},
new Abc()
{
a = 5,
b = 6,
s = "Phew"
},
new Abc()
{
a = 9,
b = 10,
s = "Phew"
},
};
list = list.MyDistinct();
}
// Extension Method
public static List<Abc> MyDistinct(this List<Abc> list)
{
List<Abc> newList = new List<Abc>();
foreach (Abc item in list)
{
Abc found = newList.FirstOrDefault(x => x.Equals(item));
if (found == null)
{
newList.Add(item);
}
else
{
if (found.s != "Keep" && item.s == "Keep")
{
newList.Remove(found);
newList.Add(item);
}
}
}
return newList;
}
}
class Abc
{
public int a, b;
public string s;
public override bool Equals(object obj)
{
Abc other = obj as Abc;
return a == other.a && b == other.b;
}
public override int GetHashCode()
{
return a.GetHashCode() ^ b.GetHashCode();
}
}
Hope it will help you..
I have a big class with a lot of properties (BigClass). I need to make a new class (SmallClass) with only some of those properties. This SmallClass must use all the overlapping properties from BigClass. What is the easiest way to do this without having to manually assign all the properties in the constructor of SmallClass like I do below:
class BigClass
{
public int A { get; }
public int B { get; }
public int C { get; }
public int D { get; }
public int E { get; }
public BigClass(int a, int b, int c, int d, int e)
{
A = a;
B = b;
C = c;
D = d;
E = e;
}
}
class SmallClass
{
public int A { get; }
public int B { get; }
public int C { get; }
public SmallClass(BigClass bigClass)
{
// I don't want to do all this manually:
A = bigClass.A;
B = bigClass.B;
C = bigClass.C;
}
}
Create a helper class:
public class Helper
{
public static void CopyItem<T>(BigClass source, T target)
{
// Need a way to rename the backing-field name to the property Name ("<A>k__BackingField" => "A")
Func<string, string> renameBackingField = key => new string(key.Skip(1).Take(key.IndexOf('>') - 1).ToArray());
// Get public source properties (change BindingFlags if you need to copy private memebers as well)
var sourceProperties = source.GetType().GetProperties().ToDictionary(item => item.Name);
// Get "missing" property setter's backing field
var targetFields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField).ToDictionary(item => renameBackingField(item.Name));
// Copy properties where target name matches the source property name
foreach(var sourceProperty in sourceProperties)
{
if (targetFields.ContainsKey(sourceProperty.Key) == false)
continue; // No match. skip
var sourceValue = sourceProperty.Value.GetValue(source);
targetFields[sourceProperty.Key].SetValue(target, sourceValue);
}
}
}
Then in your SmallClass constructor:
public SmallClass(BigClass bigClass)
{
Helper.CopyItem(bigClass, this);
}
This should work even if you only have property getters.
You can make CopyItem to work with all types by changing its declaration;
public static void CopyItem<U, T>(U source, T target)
Here is my class:
public class MyClass
{
public string Name { get; set; }
public string FaminlyName { get; set; }
public int Phone { get; set; }
}
Then I have two similar list:
List<MyClass> list1 = new List<MyClass>()
{
new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};
List<MyClass> list2 = new List<MyClass>()
{
new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};
The problem is that NUnit CollectionAssert return false always.
CollectionAssert.AreEqual(list1,list2);
Am I missing something about CollectionAssert test
The AreEqual checks for equality of the objects. Since you did not override the Equals method, it will return false in case the references are not equal.
You can solve this by overriding the Equals method of your MyClass:
public class MyClass {
public string Name { get; set; }
public string FaminlyName { get; set; }
public int Phone { get; set; }
public override bool Equals (object obj) {
MyClass mobj = obj as MyClass;
return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone);
}
}
You furthermore better override the GetHashCode method as well:
public class MyClass {
public string Name { get; set; }
public string FaminlyName { get; set; }
public int Phone { get; set; }
public override bool Equals (object obj) {
MyClass mobj = obj as MyClass;
return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone);
}
public override int GetHashCode () {
int hc = 0x00;
hc ^= (this.Name != null) ? this.Name.GetHashCode() : 0;
hc ^= (this.FaminlyName != null) ? this.FaminlyName.GetHashCode() : 0;
hc ^= this.Phone.GetHashCode();
return hc;
}
}
I have these classes in my project:
public class A
{
public A(B b, C c)
{
this.b = b;
this.c = c;
}
B b;
C c;
}
public class B
{
public B(DataRow row)
{
if (row.Table.Columns.Contains("Property3 "))
this.Property3 = row["Property3 "].ToString();
if (row.Table.Columns.Contains("Property4"))
this.Property4= row["Property4"].ToString();
}
public string Property3 { get; set; }
public string Property4{ get; set; }
public object MyToObject()
{
}
}
public class C
{
public C(DataRow row)
{
if (row.Table.Columns.Contains("Property1 "))
this.Property1 = row["Property1 "].ToString();
if (row.Table.Columns.Contains("Property2 "))
this.Property2 = row["Property2 "].ToString();
}
public string Property1 { get; set; }
public string Property2 { get; set; }
}
I want to take an object as output from MyToObject function that is declared in class A; that output object contains all of the properties of b and c, like this:
output object = {b.Property3 , b.Property4 , c.Property1 , c.Property2 }
Unless I'm missing something, you've just about got it:
public dynamic MyToObject(B b, C c)
{
return new
{
BUserName = b.UserName,
BPassword = b.PassWord,
CUserName = c.UserName,
CPassword = c.PassWord
}
}
Now that you've created a dynamic object you can use it like this:
var o = a.MyToObject(b, c);
Console.WriteLine(o.BUserName);
Try this:
public class D
{
public string UserNameB { get; set; }
public string PasswordB { get; set; }
public string UserNameC { get; set; }
public string PassWordC { get; set; }
public D(B b, C c)
{
UserNameB = b.UserName;
PasswordB = b.PassWord;
UserNameC = c.UserName;
PassWordC = c.PassWord;
}
}
and then your ToMyObject method can just be this:
public static D ToMyObject(B b, C c)
{
return new D(b, c);
}
Or you could also use a Tuple<B, C>:
public static Tuple<B, C> ToMyObject(B b, C c)
{
return Tuple.Create(b, c);
}
You could also be a bit cheeky and use anonymous objects, but that's very dangerous:
public dynamic MyToObject(B b, C c)
{
return new { UserNameB = b.UserName, PassWordB = b.PassWord,
UserNameC = c.UserName, PassWordC = c.PassWord }
}