Deep Copy of Constructor in C# [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
I'm trying to create a deep copy of object but the complier is throwing this error
As I'm beginner in C# and want to grip over these concepts of oop so your valuble answer explaining this concept would be highly appreciated

We would need to see the ctor of the quadratic class, it seems you are missing an overload that accepts one parameter.
Like so.
namespace ConsoleApp1
{
internal class Class1
{
public Class1()
{
}
public Class1(int input)
{
}
}
}

I assume that your Quadratic class doesn't have an overload for its own type to create deep copy. You have few options to create deep copy of your classes.
Create the class by setting its properties yourself in the constructor
Use the MemberwiseClone() method.
Serialize it and deserialize it again. You can do this with built-in JSON serializer that's located in the System.Text.Json namespace or with Protobuf. (Do NOT use BinaryFormatter to do this. Check this article for more information.)
public class Quadratic
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public Quadratic()
{
}
public Quadratic(Quadratic quadraticToCopy)
{
A = quadraticToCopy.A;
B = quadraticToCopy.B;
C = quadraticToCopy.C;
}
public Quadratic CreateDeepCopy1() => new Quadratic(this);
public Quadratic CreateDeepCopy2() => (Quadratic)this.MemberwiseClone();
}
And then you can use it like this;
var originalQuadratic = new Quadratic();
originalQuadratic.Input();
originalQuadratic.Display();
var deepCopiedQuadratic1 = originalQuadratic.CreateDeepCopy1();
var deepCopiedQuadratic2 = originalQuadratic.CreateDeepCopy2();

Related

Method to return a List<T> from a List<OwnStruct>, where List<T> then contains only one Property of all OwnStructs in List (C#) [duplicate]

This question already has answers here:
convert a list of objects from one type to another using lambda expression
(14 answers)
Closed 1 year ago.
I'm struggling with this a little.
I have a List<HeadStruc_Table> within my program.
The Class HeadStruct looks like following:
public partial class HeadStruct_Table : IComparable<HeadStruct_Table>
{
public string colName { get; set; }
public string colName_edit { get; set; }
public string alternativeNames { get; set; }
public int Table_ID { get; set; }
public bool colFound { get; set; }
public CheckBox cBox { get; set; }
I don't know how to create a method with parameters (List<HeadStruct_Table>, HeadStruct_Table.colName) that then returns a List<TypeOf(HeadStruct_Table.colName)> containing only the values of colName in this specific case.
Of course it should work for the bool and even CheckBox property as well.
As parameter HeadStruct_Table.colName doesn't work right now, as it is declared as just public and not public static, do i have to declare it as public static or is there any other chance to pass the specific property. Maybe by using a predicate?
That's the way it maybe could look like later?
public static IList<T> getList<T>(List<HeadStruct_Table> list, Func<HeadStruct_Table, T> getType)
{
var newList = new List<T>();
I just don't know how to get the special property and then, in the method, just read out those values. I wouldn't like to work with a string as parameter if it works without.
Anyone who has an idea?
That is my first question. I'm open for any advice to improve asking a question in here. Thank You.
LINQ's Enumerable.Select method already does what you want:
var newList = list.Select(x => x.colName).ToList();

How to implement a function to select items only of specific types?

Context
I have a Question class. It has three subclasses:
ChoiceQuestion
ShortTextQuestion
LongTextQuestion
I have a Repository class which has an IEnumerable<Question>.
Code
Question class hierarchy and container class Repository:
class Question {}
class ChoiceQuestion : Question {}
class ShortTextQuestion : Question {}
class LongTextQuestion : Question {}
class Repository
{
IEnumerable<Question> Questions { get; set; }
}
Problem
I want to pick few questions for a Questionnaire from these repositories.
I have an IQuestionnaireBuilder which has an AddSource() method that helps configure which repository to pick questions from and how to pick them. I have the QuestionnaireSource class which holds this configuration.
Currently, I am able to specify, which repository to pick from, how many questions to pick of each difficulty. I want to specify that it should only pick questions which are of specific subtypes.
For instance, the questions to be picked must be either ChoiceQuestion or ShortTextQuestion. I have come across System.Type, but I want to restrict the types such that they must derive from Question.
Code
IQuestionnaireBuilder
interface IQuestionnaireBuilder
{
IQuestionnaireBuilder AddSource(Action<QuestionnaireSource> source);
}
QuestionnaireSource
class QuestionnaireSource
{
public Repository Repository { get; set; }
public IDictionary<QuestionDifficulty, int> { get; set; }
// <Property/method to configure which subclasses to include, they must derive from Question>
}
QuestionDifficulty
enum QuestionDifficulty
{ Easy, Medium, Hard }
IQuestionnaireBuilder builder = new QuestionnaireBuilder();
Repository repo1 = someExternalProvider.GetRepo(1);
Repository repo2 = someExternalProvider.GetRepo(2);
builder
.AddSource(source => {
source.Repository = repo1;
source.Count[QuestionDifficulty.Easy] = 10;
source.Count[QuestionDifficulty.Medium] = 7;
source.Count[QuestionDifficulty.Hard] = 3;
source.PickOnlySpecificSubclassesOfQuestion() // how to implement this?
})
.AddSource(source => {
source.Repository = repo2;
source.Count[QuestionDifficulty.Easy] = 30;
source.Count[QuestionDifficulty.Medium] = 15;
source.Count[QuestionDifficulty.Hard] = 5;
source.PickOnlySpecificSubclassesOfQuestion() // how to implement this?
})
In the above snippet, how do I implement the PickOnlySpecificSubclassesOfQuestion() part?
One way to do it would be to make your PickOnlySpecificSubclassesOfQuestion generic, and pass it one argument representing the type of question you want.
public void PickOnlySpecificSubclassesOfQuestion<T>()
where T : Question
Inside that method, you could get a System.Type representing the requested type of question like this:
Type desiredTypeOfQuestion = typeof(T);
Then, given an IEnumerable of questions containing questions of all different types, you could use Linq and Reflection to find the ones that are assignable from the desired type:
return myQuestions.Where(q => q.GetType().IsAssignableFrom(desiredTypeOfQuestion));
I'm sure there are other approaches that would work too, but this is the one that sprang to mind most easily.
This is how I've done it using delegates. I added a Filter property to QuestionnaireSource of type System.Predicate<T>. System.Predicate<T> is a delegate defined as follows:
public delegate bool Predicate<in T>(T obj);
You can also use Func<Question, bool> or your own delegate type.
In my QuestionnaireSource class, I added the Filter property:
class QuestionnaireSource
{
public Repository Repository { get; set; }
public IDictionary<QuestionDifficulty, int> { get; set; }
public Predicate<Question> Filter { get; set; }
}
Now I can pass a lambda expression such as the following:
question => question is ChoiceQuestion
Now I can filter more flexibly thanks to C#'s pattern matching with is.
I can configure it as following using the AddSource() method of QuestionnaireBuilder when building my questionnaire:
builder
.AddSource(source => {
source.Repository = repo1;
source.Count[QuestionDifficulty.Easy] = 10;
source.Count[QuestionDifficulty.Medium] = 7;
source.Count[QuestionDifficulty.Hard] = 3;
source.Filter = question => question is ChoiceQuestion
});
Now I can filter out or include multiple types:
question => question is ChoiceQuestion || question is ShortTextQuestion
Not only that, I can also filter using other criteria, such as the question text:
question => question.Text.Trim().StartsWith("What");
#benjamin's answer also works if you want to select just one subtype but this filter approach seems to be a bit more flexible if multiple types are to be selected or ignored.

How can I deserialize a simple Json with square brackets in c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I don´t know what I´m doing wrong, but this is the Json I´m trying to read:
[{
"object":
{
"Weigh": 4000
}
}]
I really don´t know why I need the "object": part, but if I remove it, the code doesn´t work.
Here is my API Rest:
[HttpPost]
public string GetMixerTime([FromBody]JsonObject<WeighMix>[] json)
{
IList<WeighMix> listawm = JsonConvert.DeserializeObject<List<WeighMix>>(json.ToString());
return listawm.ToString();
}
WeighMix class:
public class WeighMix
{
public double Weigh { get; set; }
public WeighMix()
{
}
public WeighMix(double weigh)
{
Weigh = weigh;
}
}
Thanks a lot.
The Square Brackets signifies Arrays in Json. Your Json is an array of type (say) A, which has a single property called object of type B (B matches the definition of WeighMix).
You need to change your class declaration as
public class RootObject
{
[JsonProperty("object")]
public WeighMix Object{get;set;}
}
// Define other methods and classes here
public class WeighMix
{
public double Weigh { get; set; }
public WeighMix()
{
}
public WeighMix(double weigh)
{
Weigh = weigh;
}
}
You can now deserialize using
var result = JsonConvert.DeserializeObject<List<RootObject>>(json);
Sample Input
var json = #"[ { 'object': { 'weigh': 4000.0 }, 'json': '{\'Weigh\':4000.0}' } ]";
Sample Output

Framework for handling serialization in "key:value;key:value;key:value;key:value;" format [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Of course it's easy to write the code to deserialize from this format. I've already done it, but I don't like.
The single responsibility principle states that I should have a generic class that worries only about this kind of serialization. And the task is generic enough to be coped by a framework.
If you converted it to a JSON string like (which should be easy)
var jsonArray = “[{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}]”;
then you could easily deserialize it with Json.NET into whatever you want and Json.NET takes care of converting the values to the right types for you:
MyType1[] result = JsonConvert.Deserialize<MyType1[]>(jsonArray);
MyType2[] result = JsonConvert.Deserialize<MyType2[]>(jsonArray);
public class MyType1
{
public string key { get; set; }
public string value { get; set; }
}
public class MyType2
{
public string key { get; set; }
public double value { get; set; }
}
or even just as a dictionary (I hope I have the syntax correct, I didn't test it):
var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = JsonConvert.Deserialize<Dictionary<string, string>>(jsonDic);
The single responsibility class (just as an example):
public class KeyValueParser
{
public static TResult ParseKeyValueString<TResult>(string keyValueString)
{
keyValueString = ConvertToJson(keyValueString);
TResul result = JsonConvert.DeserializeObject<TResult>(keyValueString);
return result;
}
private static string ConvertToJson(string keyValueString)
{
// convert keyValueString to json
}
}
usage
var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = KeyValueParser.ParseKeyValueString<Dictionary<string, string>>(jsonDic);
I don't really understand the question.
If it is something your program does a lot then move the function to some area that it is easy to get too (or a nuget package if a lot of your systems need it). If it happens in one place in your code put it quite close to that place.

Trying to convert a xml file to an object [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I was wondering what your opinion about this would be. I'm trying to convert an xml file to a .net object. It's a xml file from the World of Warcraft armory. Here is an example.
<?xml version="1.0" encoding="UTF-8"?>
<baseStats>
<strength attack="48" base="48" block="-1" effective="58"/>
<agility armor="114" attack="-1" base="47" critHitPercent="4.27" effective="57"/>
<stamina base="70" effective="1186" health="11680" petBonus="-1"/>
<intellect base="198" critHitPercent="10.41" effective="1529" mana="22655" petBonus="-1"/>
<spirit base="190" effective="770" healthRegen="39" manaRegen="503"/>
<armor base="2150" effective="2150" percent="12.37" petBonus="-1"/>
</baseStats>
I've thought of 2 ways to convert this to an object and I'd like to hear your opinion about it. Ill show them.
class BaseStats{
public int StrengthAttack{get;set;}
public int StrengthBase{get;set;}
public int StrengthBlock{get;set;}
...
public int ArmorBase{get;set;}
public int ArmorEffective{get;set;}
...
}
or
class BaseStats{
public Strength Strength{get;set;}
public Armor Armor{get;set;}
public class Strength{
public int Attack{get;set;}
public int Base{get;set;}
public int Block{get;set;}
}
public class Armor{
public int Base{get;set;}
public int Effective{get;set;}
}
}
Do you see what I'm trying here. What would be your opinion about each of those ways. Or can you think of any others?
Classless Design using an Anonymous Type
Here's another way, with .NET 3.5, if you don't want to design an explicit class you can build the object dynamically as an anonymous type; one caveat being the object properties are read-only after being initialized.
Use the XML LINQ classes to query the XML content with.
using System;
using System.IO;
using System.Xml.Linq;
Load up the XML string and query it to create an object.
// 1. Load your string into a document.
XDocument xdoc = XDocument.Load(new StringReader(my_WoW_XML_String));
// 2. Create the anonymous type...
var statsObject = new
{
StrengthInfo = new
{
Attack = int.Parse(xdoc.Element("strength").Element("attack").Value),
Base = int.Parse(xdoc.Element("strength").Element("base").Value),
Block = int.Parse(xdoc.Element("strength").Element("block").Value),
Effective = int.Parse(xdoc.Element("strength").Element("effective").Value),
},
AgilityInfo = new
{
Armor = int.Parse(xdoc.Element("agility").Element("armor").Value),
Attack = int.Parse(xdoc.Element("agility").Element("attack").Value),
Base = int.Parse(xdoc.Element("agility").Element("base").Value),
CritHitPercent = int.Parse(xdoc.Element("agility").Element("critHitPercent").Value),
Effective = int.Parse(xdoc.Element("agility").Element("effective").Value),
}
// Do the same with <spirit> and <armor> elements, etc.
// Include only the properties you want from the XML.
}; // end anonymous object.
Use your anonymous object normally like so:
Console.Write("strength: attack={0}, effective={1}; armor agility={2}",
statsObject.StrengthInfo.Attack,
statsObject.StrengthInfo.Effective,
statsObject.AgilityInfo.Armor);
// Do whatever you want with the object version of WoW stats.
If you have multiple XML files to process with the same schema then just wrap all the above in a loop to process one at a time.
If you have the XSD schema (or can create one), I've used LinqToXsd to create some quick objects. The nice thing about LinqToXsd is that it creates methods you can use to easily parse XML into your objects.
Microsoft has released it as Open Source - and you can simply use a command-line call to pass in your .xsd and it will generate a .cs file with all of your classes.
class CElement
{
public int? attack { get; set; }
public int? base { get; set; }
public int? block { get; set; }
public int? effective { get; set; }
public int? petBonus { get; set; }
public int? mana { get; set; }
public int? healthRegen { get; set; }
public int? manaRegen { get; set; }
public double? critHitPercent { get; set; }
public double? percent { get; set; }
}
class CBaseStats
{
public CElement strength;
public CElement agility;
public CElement stamina;
public CElement intellect;
public CElement spirit;
public CElement armor;
}
If you got complete xml,
1. generate xsd from xml using the xsd.exe tool
2. generate class from the generated xsd using xsd.exe tool
http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx

Categories