How can get Property and the Value in a generic Class? The Next CEO of Stack OverflowHow do you give a C# Auto-Property a default value?Use of var keyword in C#How do I use reflection to call a generic method?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to create a generic array in Java?How to get the type of T from a member of a generic class or method?Get int value from enum in C#How do I generate a random int number?How to Sort a List<T> by a property in the objectHow to get a class instance of generics type T

Traduction de « Life is a roller coaster »

Expressing the idea of having a very busy time

How do I fit a non linear curve?

Computationally populating tables with probability data

Decide between Polyglossia and Babel for LuaLaTeX in 2019

Does higher Oxidation/ reduction potential translate to higher energy storage in battery?

How to use ReplaceAll on an expression that contains a rule

Inexact numbers as keys in Association?

How to get the last not-null value in an ordered column of a huge table?

Scary film where a woman has vaginal teeth

Could a dragon use its wings to swim?

Strange use of "whether ... than ..." in official text

Why is information "lost" when it got into a black hole?

Which one is the true statement?

Why am I getting "Static method cannot be referenced from a non static context: String String.valueOf(Object)"?

Expectation in a stochastic differential equation

My ex-girlfriend uses my Apple ID to login to her iPad, do I have to give her my Apple ID password to reset it?

Can someone explain this formula for calculating Manhattan distance?

Help/tips for a first time writer?

Towers in the ocean; How deep can they be built?

Are the names of these months realistic?

Calculate the Mean mean of two numbers

Is it okay to majorly distort historical facts while writing a fiction story?

Lucky Feat: How can "more than one creature spend a luck point to influence the outcome of a roll"?



How can get Property and the Value in a generic Class?



The Next CEO of Stack OverflowHow do you give a C# Auto-Property a default value?Use of var keyword in C#How do I use reflection to call a generic method?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to create a generic array in Java?How to get the type of T from a member of a generic class or method?Get int value from enum in C#How do I generate a random int number?How to Sort a List<T> by a property in the objectHow to get a class instance of generics type T










0















Here is where is call the function and create the object
Maybe this way you can see what I'm trying to do



 class Program 


static void Main(string[] args)


//here I create an object and pass the type Person
var Crud = new Crud<Person>();
//here I invoke the method Create and pass the object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone", Age = 24 );
//here I invoke the method again to Create and pass an other object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone2", Age = 24 );

With this method Read() I get the List created back
var Lista = Crud.Read();
Lista.ForEach((x) => Console.WriteLine("0 1",x.Id.ToString(), x.Name));

/* Here is where my problem starts I'm sending an new object that will replace the object with Id =1 passed by constructor */
Crud.Update(new Person(1) Name = "someone3", Age = 20 );




Console.ReadKey();




This is where I'm trying to do using this class



//This class is a generic where T is the type "Person" that was passed



 public class Crud <T>: ICrud <T> 

private List <T> List = new List <T> ();

public MessageError Update(T object)
//Here it doesn't work its impossible to get the Id property sense its an generic object at this point
List.RemoveAll(x => x.Id == t.Id);
List.Add(t);
return new MessageError
Status = Status.Sucessful
;




My concrete type using in my code



 public class Person

public int Id get; private set;
public string Name get; set;
public int Age get; set;
//Here I set the id for each object
public Person(int _id)

Id = _id;




Here you can see the interface



 interface ICrud<T>

MessageError Create(T t);
List<T> Read();
MessageError Update(T t);
MessageError Delete(int Id);



I try now use like but still dont work



 List.RemoveAll(x => x.GetProperty("Id") == t.GetProperty("Id"));


I guess that is the solution for it



public MessageError Update(T t)

var type = t.GetType();

PropertyInfo prop = type.GetProperty("Id");

var value = prop.GetValue(t);
List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
List.Add(t);
return new MessageError

Status = Status.Sucessful
;










share|improve this question



















  • 2





    Commonly-accepted naming conventions for C# dictate that local variables should be titled camel-case. It's very confusing to see List.Add(t).

    – Kenneth K.
    Mar 8 at 16:54











  • Its a generic class so for exemple if Crud.Update(new Person(1)); so there would be public MessageError Update(Person person) but the class is generic

    – Amadeu Antunes
    Mar 8 at 16:57











  • I give you all the information now

    – Amadeu Antunes
    Mar 8 at 17:12











  • If you have any questions please let me know

    – Amadeu Antunes
    Mar 8 at 17:12






  • 1





    You need a generic constraint.

    – BJ Myers
    Mar 8 at 17:15















0















Here is where is call the function and create the object
Maybe this way you can see what I'm trying to do



 class Program 


static void Main(string[] args)


//here I create an object and pass the type Person
var Crud = new Crud<Person>();
//here I invoke the method Create and pass the object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone", Age = 24 );
//here I invoke the method again to Create and pass an other object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone2", Age = 24 );

With this method Read() I get the List created back
var Lista = Crud.Read();
Lista.ForEach((x) => Console.WriteLine("0 1",x.Id.ToString(), x.Name));

/* Here is where my problem starts I'm sending an new object that will replace the object with Id =1 passed by constructor */
Crud.Update(new Person(1) Name = "someone3", Age = 20 );




Console.ReadKey();




This is where I'm trying to do using this class



//This class is a generic where T is the type "Person" that was passed



 public class Crud <T>: ICrud <T> 

private List <T> List = new List <T> ();

public MessageError Update(T object)
//Here it doesn't work its impossible to get the Id property sense its an generic object at this point
List.RemoveAll(x => x.Id == t.Id);
List.Add(t);
return new MessageError
Status = Status.Sucessful
;




My concrete type using in my code



 public class Person

public int Id get; private set;
public string Name get; set;
public int Age get; set;
//Here I set the id for each object
public Person(int _id)

Id = _id;




Here you can see the interface



 interface ICrud<T>

MessageError Create(T t);
List<T> Read();
MessageError Update(T t);
MessageError Delete(int Id);



I try now use like but still dont work



 List.RemoveAll(x => x.GetProperty("Id") == t.GetProperty("Id"));


I guess that is the solution for it



public MessageError Update(T t)

var type = t.GetType();

PropertyInfo prop = type.GetProperty("Id");

var value = prop.GetValue(t);
List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
List.Add(t);
return new MessageError

Status = Status.Sucessful
;










share|improve this question



















  • 2





    Commonly-accepted naming conventions for C# dictate that local variables should be titled camel-case. It's very confusing to see List.Add(t).

    – Kenneth K.
    Mar 8 at 16:54











  • Its a generic class so for exemple if Crud.Update(new Person(1)); so there would be public MessageError Update(Person person) but the class is generic

    – Amadeu Antunes
    Mar 8 at 16:57











  • I give you all the information now

    – Amadeu Antunes
    Mar 8 at 17:12











  • If you have any questions please let me know

    – Amadeu Antunes
    Mar 8 at 17:12






  • 1





    You need a generic constraint.

    – BJ Myers
    Mar 8 at 17:15













0












0








0








Here is where is call the function and create the object
Maybe this way you can see what I'm trying to do



 class Program 


static void Main(string[] args)


//here I create an object and pass the type Person
var Crud = new Crud<Person>();
//here I invoke the method Create and pass the object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone", Age = 24 );
//here I invoke the method again to Create and pass an other object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone2", Age = 24 );

With this method Read() I get the List created back
var Lista = Crud.Read();
Lista.ForEach((x) => Console.WriteLine("0 1",x.Id.ToString(), x.Name));

/* Here is where my problem starts I'm sending an new object that will replace the object with Id =1 passed by constructor */
Crud.Update(new Person(1) Name = "someone3", Age = 20 );




Console.ReadKey();




This is where I'm trying to do using this class



//This class is a generic where T is the type "Person" that was passed



 public class Crud <T>: ICrud <T> 

private List <T> List = new List <T> ();

public MessageError Update(T object)
//Here it doesn't work its impossible to get the Id property sense its an generic object at this point
List.RemoveAll(x => x.Id == t.Id);
List.Add(t);
return new MessageError
Status = Status.Sucessful
;




My concrete type using in my code



 public class Person

public int Id get; private set;
public string Name get; set;
public int Age get; set;
//Here I set the id for each object
public Person(int _id)

Id = _id;




Here you can see the interface



 interface ICrud<T>

MessageError Create(T t);
List<T> Read();
MessageError Update(T t);
MessageError Delete(int Id);



I try now use like but still dont work



 List.RemoveAll(x => x.GetProperty("Id") == t.GetProperty("Id"));


I guess that is the solution for it



public MessageError Update(T t)

var type = t.GetType();

PropertyInfo prop = type.GetProperty("Id");

var value = prop.GetValue(t);
List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
List.Add(t);
return new MessageError

Status = Status.Sucessful
;










share|improve this question
















Here is where is call the function and create the object
Maybe this way you can see what I'm trying to do



 class Program 


static void Main(string[] args)


//here I create an object and pass the type Person
var Crud = new Crud<Person>();
//here I invoke the method Create and pass the object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone", Age = 24 );
//here I invoke the method again to Create and pass an other object "Person"
Crud.Create(new Person(Crud.Id) Name = "Sameone2", Age = 24 );

With this method Read() I get the List created back
var Lista = Crud.Read();
Lista.ForEach((x) => Console.WriteLine("0 1",x.Id.ToString(), x.Name));

/* Here is where my problem starts I'm sending an new object that will replace the object with Id =1 passed by constructor */
Crud.Update(new Person(1) Name = "someone3", Age = 20 );




Console.ReadKey();




This is where I'm trying to do using this class



//This class is a generic where T is the type "Person" that was passed



 public class Crud <T>: ICrud <T> 

private List <T> List = new List <T> ();

public MessageError Update(T object)
//Here it doesn't work its impossible to get the Id property sense its an generic object at this point
List.RemoveAll(x => x.Id == t.Id);
List.Add(t);
return new MessageError
Status = Status.Sucessful
;




My concrete type using in my code



 public class Person

public int Id get; private set;
public string Name get; set;
public int Age get; set;
//Here I set the id for each object
public Person(int _id)

Id = _id;




Here you can see the interface



 interface ICrud<T>

MessageError Create(T t);
List<T> Read();
MessageError Update(T t);
MessageError Delete(int Id);



I try now use like but still dont work



 List.RemoveAll(x => x.GetProperty("Id") == t.GetProperty("Id"));


I guess that is the solution for it



public MessageError Update(T t)

var type = t.GetType();

PropertyInfo prop = type.GetProperty("Id");

var value = prop.GetValue(t);
List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
List.Add(t);
return new MessageError

Status = Status.Sucessful
;







c# generics






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 17:42







Amadeu Antunes

















asked Aug 13 '18 at 16:24









Amadeu AntunesAmadeu Antunes

457526




457526







  • 2





    Commonly-accepted naming conventions for C# dictate that local variables should be titled camel-case. It's very confusing to see List.Add(t).

    – Kenneth K.
    Mar 8 at 16:54











  • Its a generic class so for exemple if Crud.Update(new Person(1)); so there would be public MessageError Update(Person person) but the class is generic

    – Amadeu Antunes
    Mar 8 at 16:57











  • I give you all the information now

    – Amadeu Antunes
    Mar 8 at 17:12











  • If you have any questions please let me know

    – Amadeu Antunes
    Mar 8 at 17:12






  • 1





    You need a generic constraint.

    – BJ Myers
    Mar 8 at 17:15












  • 2





    Commonly-accepted naming conventions for C# dictate that local variables should be titled camel-case. It's very confusing to see List.Add(t).

    – Kenneth K.
    Mar 8 at 16:54











  • Its a generic class so for exemple if Crud.Update(new Person(1)); so there would be public MessageError Update(Person person) but the class is generic

    – Amadeu Antunes
    Mar 8 at 16:57











  • I give you all the information now

    – Amadeu Antunes
    Mar 8 at 17:12











  • If you have any questions please let me know

    – Amadeu Antunes
    Mar 8 at 17:12






  • 1





    You need a generic constraint.

    – BJ Myers
    Mar 8 at 17:15







2




2





Commonly-accepted naming conventions for C# dictate that local variables should be titled camel-case. It's very confusing to see List.Add(t).

– Kenneth K.
Mar 8 at 16:54





Commonly-accepted naming conventions for C# dictate that local variables should be titled camel-case. It's very confusing to see List.Add(t).

– Kenneth K.
Mar 8 at 16:54













Its a generic class so for exemple if Crud.Update(new Person(1)); so there would be public MessageError Update(Person person) but the class is generic

– Amadeu Antunes
Mar 8 at 16:57





Its a generic class so for exemple if Crud.Update(new Person(1)); so there would be public MessageError Update(Person person) but the class is generic

– Amadeu Antunes
Mar 8 at 16:57













I give you all the information now

– Amadeu Antunes
Mar 8 at 17:12





I give you all the information now

– Amadeu Antunes
Mar 8 at 17:12













If you have any questions please let me know

– Amadeu Antunes
Mar 8 at 17:12





If you have any questions please let me know

– Amadeu Antunes
Mar 8 at 17:12




1




1





You need a generic constraint.

– BJ Myers
Mar 8 at 17:15





You need a generic constraint.

– BJ Myers
Mar 8 at 17:15












2 Answers
2






active

oldest

votes


















2














I think maybe you're simply missing a step. CRUD stands for Create, Read, Update, Delete. Here, you're creating a couple of bits of data, reading everything in, but then trying to send an Update directly to the data store. What you should do, is read in your Persons, change one or more of their properties, then Crud.Update(person), which in turn will know that the person needs Updating rather than Creating in the data store.



In fact, it's fairly normal practice to differentiate between Create and Update based on whether the entity has a value for it's ID or not. In which case, your code might look like this:



class Program 

static void Main(string[] args)

TestClass testClass = new TestClass();
testClass.Create();

var crud = new Crud<Person>();

// Note we're not specifying an ID for *new* entities, the Crud class needs to assign it upon saving
crud.Create(new Person() Name = "Someone", Age = 24 );
crud.Create(new Person() Name = "Someone2", Age = 24 );

var list = crud.ReadAll();
list.ForEach(x => Console.WriteLine("0 1", x.Id, x.Name));

var person1 = list.Single(x => x.Id == 1);
person1.Name = "Someone3";
person1.Age = 20;

Crud.Update(person1);

Console.ReadKey();




Although there is a further optimisation to be made here. This will load all objects from the data store into the memory of the application, which will then go through each one until it finds the one it wants. It would be better if the data store being used could do that for you. In which case you'd be able to do something more like var person1 = crud.FindById(1). There are loads of other techniques for this, but I don't want to complicate this answer any further.






share|improve this answer























  • I used the constructor for pass the Id 'Person(Crud.Id)'

    – Amadeu Antunes
    Mar 8 at 17:26












  • if you check my class Person you will see the constructor

    – Amadeu Antunes
    Mar 8 at 17:27











  • public Person(int _id) Id = _id;

    – Amadeu Antunes
    Mar 8 at 17:28











  • Yeah I'm literally suggesting that the ID is set by something closer to the database, therefore is not a requirement to initialise a new Person, therefore shouldn't be part of the constructor. If you don't want to modify your design you're going to struggle to solve your problem.

    – Neil Barnwell
    Mar 8 at 17:30






  • 2





    In fact what you should be doing really is using an ORM where this is all a solved problem, and leaves you do get on with solving unsolved problems in your business. Unless this is a homework question, I suppose.

    – Neil Barnwell
    Mar 8 at 17:31


















1














public MessageError Update(T t)

/* I used this why to the the property in my last version I get the name of property by Parameter */
var type = t.GetType();
PropertyInfo prop = type.GetProperty("Id");

var value = prop.GetValue(t);
List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
List.Add(t);
return new MessageError

Status = Status.Sucessful
;






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51826712%2fhow-can-get-property-and-the-value-in-a-generic-class%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    I think maybe you're simply missing a step. CRUD stands for Create, Read, Update, Delete. Here, you're creating a couple of bits of data, reading everything in, but then trying to send an Update directly to the data store. What you should do, is read in your Persons, change one or more of their properties, then Crud.Update(person), which in turn will know that the person needs Updating rather than Creating in the data store.



    In fact, it's fairly normal practice to differentiate between Create and Update based on whether the entity has a value for it's ID or not. In which case, your code might look like this:



    class Program 

    static void Main(string[] args)

    TestClass testClass = new TestClass();
    testClass.Create();

    var crud = new Crud<Person>();

    // Note we're not specifying an ID for *new* entities, the Crud class needs to assign it upon saving
    crud.Create(new Person() Name = "Someone", Age = 24 );
    crud.Create(new Person() Name = "Someone2", Age = 24 );

    var list = crud.ReadAll();
    list.ForEach(x => Console.WriteLine("0 1", x.Id, x.Name));

    var person1 = list.Single(x => x.Id == 1);
    person1.Name = "Someone3";
    person1.Age = 20;

    Crud.Update(person1);

    Console.ReadKey();




    Although there is a further optimisation to be made here. This will load all objects from the data store into the memory of the application, which will then go through each one until it finds the one it wants. It would be better if the data store being used could do that for you. In which case you'd be able to do something more like var person1 = crud.FindById(1). There are loads of other techniques for this, but I don't want to complicate this answer any further.






    share|improve this answer























    • I used the constructor for pass the Id 'Person(Crud.Id)'

      – Amadeu Antunes
      Mar 8 at 17:26












    • if you check my class Person you will see the constructor

      – Amadeu Antunes
      Mar 8 at 17:27











    • public Person(int _id) Id = _id;

      – Amadeu Antunes
      Mar 8 at 17:28











    • Yeah I'm literally suggesting that the ID is set by something closer to the database, therefore is not a requirement to initialise a new Person, therefore shouldn't be part of the constructor. If you don't want to modify your design you're going to struggle to solve your problem.

      – Neil Barnwell
      Mar 8 at 17:30






    • 2





      In fact what you should be doing really is using an ORM where this is all a solved problem, and leaves you do get on with solving unsolved problems in your business. Unless this is a homework question, I suppose.

      – Neil Barnwell
      Mar 8 at 17:31















    2














    I think maybe you're simply missing a step. CRUD stands for Create, Read, Update, Delete. Here, you're creating a couple of bits of data, reading everything in, but then trying to send an Update directly to the data store. What you should do, is read in your Persons, change one or more of their properties, then Crud.Update(person), which in turn will know that the person needs Updating rather than Creating in the data store.



    In fact, it's fairly normal practice to differentiate between Create and Update based on whether the entity has a value for it's ID or not. In which case, your code might look like this:



    class Program 

    static void Main(string[] args)

    TestClass testClass = new TestClass();
    testClass.Create();

    var crud = new Crud<Person>();

    // Note we're not specifying an ID for *new* entities, the Crud class needs to assign it upon saving
    crud.Create(new Person() Name = "Someone", Age = 24 );
    crud.Create(new Person() Name = "Someone2", Age = 24 );

    var list = crud.ReadAll();
    list.ForEach(x => Console.WriteLine("0 1", x.Id, x.Name));

    var person1 = list.Single(x => x.Id == 1);
    person1.Name = "Someone3";
    person1.Age = 20;

    Crud.Update(person1);

    Console.ReadKey();




    Although there is a further optimisation to be made here. This will load all objects from the data store into the memory of the application, which will then go through each one until it finds the one it wants. It would be better if the data store being used could do that for you. In which case you'd be able to do something more like var person1 = crud.FindById(1). There are loads of other techniques for this, but I don't want to complicate this answer any further.






    share|improve this answer























    • I used the constructor for pass the Id 'Person(Crud.Id)'

      – Amadeu Antunes
      Mar 8 at 17:26












    • if you check my class Person you will see the constructor

      – Amadeu Antunes
      Mar 8 at 17:27











    • public Person(int _id) Id = _id;

      – Amadeu Antunes
      Mar 8 at 17:28











    • Yeah I'm literally suggesting that the ID is set by something closer to the database, therefore is not a requirement to initialise a new Person, therefore shouldn't be part of the constructor. If you don't want to modify your design you're going to struggle to solve your problem.

      – Neil Barnwell
      Mar 8 at 17:30






    • 2





      In fact what you should be doing really is using an ORM where this is all a solved problem, and leaves you do get on with solving unsolved problems in your business. Unless this is a homework question, I suppose.

      – Neil Barnwell
      Mar 8 at 17:31













    2












    2








    2







    I think maybe you're simply missing a step. CRUD stands for Create, Read, Update, Delete. Here, you're creating a couple of bits of data, reading everything in, but then trying to send an Update directly to the data store. What you should do, is read in your Persons, change one or more of their properties, then Crud.Update(person), which in turn will know that the person needs Updating rather than Creating in the data store.



    In fact, it's fairly normal practice to differentiate between Create and Update based on whether the entity has a value for it's ID or not. In which case, your code might look like this:



    class Program 

    static void Main(string[] args)

    TestClass testClass = new TestClass();
    testClass.Create();

    var crud = new Crud<Person>();

    // Note we're not specifying an ID for *new* entities, the Crud class needs to assign it upon saving
    crud.Create(new Person() Name = "Someone", Age = 24 );
    crud.Create(new Person() Name = "Someone2", Age = 24 );

    var list = crud.ReadAll();
    list.ForEach(x => Console.WriteLine("0 1", x.Id, x.Name));

    var person1 = list.Single(x => x.Id == 1);
    person1.Name = "Someone3";
    person1.Age = 20;

    Crud.Update(person1);

    Console.ReadKey();




    Although there is a further optimisation to be made here. This will load all objects from the data store into the memory of the application, which will then go through each one until it finds the one it wants. It would be better if the data store being used could do that for you. In which case you'd be able to do something more like var person1 = crud.FindById(1). There are loads of other techniques for this, but I don't want to complicate this answer any further.






    share|improve this answer













    I think maybe you're simply missing a step. CRUD stands for Create, Read, Update, Delete. Here, you're creating a couple of bits of data, reading everything in, but then trying to send an Update directly to the data store. What you should do, is read in your Persons, change one or more of their properties, then Crud.Update(person), which in turn will know that the person needs Updating rather than Creating in the data store.



    In fact, it's fairly normal practice to differentiate between Create and Update based on whether the entity has a value for it's ID or not. In which case, your code might look like this:



    class Program 

    static void Main(string[] args)

    TestClass testClass = new TestClass();
    testClass.Create();

    var crud = new Crud<Person>();

    // Note we're not specifying an ID for *new* entities, the Crud class needs to assign it upon saving
    crud.Create(new Person() Name = "Someone", Age = 24 );
    crud.Create(new Person() Name = "Someone2", Age = 24 );

    var list = crud.ReadAll();
    list.ForEach(x => Console.WriteLine("0 1", x.Id, x.Name));

    var person1 = list.Single(x => x.Id == 1);
    person1.Name = "Someone3";
    person1.Age = 20;

    Crud.Update(person1);

    Console.ReadKey();




    Although there is a further optimisation to be made here. This will load all objects from the data store into the memory of the application, which will then go through each one until it finds the one it wants. It would be better if the data store being used could do that for you. In which case you'd be able to do something more like var person1 = crud.FindById(1). There are loads of other techniques for this, but I don't want to complicate this answer any further.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 8 at 17:22









    Neil BarnwellNeil Barnwell

    29.2k24130202




    29.2k24130202












    • I used the constructor for pass the Id 'Person(Crud.Id)'

      – Amadeu Antunes
      Mar 8 at 17:26












    • if you check my class Person you will see the constructor

      – Amadeu Antunes
      Mar 8 at 17:27











    • public Person(int _id) Id = _id;

      – Amadeu Antunes
      Mar 8 at 17:28











    • Yeah I'm literally suggesting that the ID is set by something closer to the database, therefore is not a requirement to initialise a new Person, therefore shouldn't be part of the constructor. If you don't want to modify your design you're going to struggle to solve your problem.

      – Neil Barnwell
      Mar 8 at 17:30






    • 2





      In fact what you should be doing really is using an ORM where this is all a solved problem, and leaves you do get on with solving unsolved problems in your business. Unless this is a homework question, I suppose.

      – Neil Barnwell
      Mar 8 at 17:31

















    • I used the constructor for pass the Id 'Person(Crud.Id)'

      – Amadeu Antunes
      Mar 8 at 17:26












    • if you check my class Person you will see the constructor

      – Amadeu Antunes
      Mar 8 at 17:27











    • public Person(int _id) Id = _id;

      – Amadeu Antunes
      Mar 8 at 17:28











    • Yeah I'm literally suggesting that the ID is set by something closer to the database, therefore is not a requirement to initialise a new Person, therefore shouldn't be part of the constructor. If you don't want to modify your design you're going to struggle to solve your problem.

      – Neil Barnwell
      Mar 8 at 17:30






    • 2





      In fact what you should be doing really is using an ORM where this is all a solved problem, and leaves you do get on with solving unsolved problems in your business. Unless this is a homework question, I suppose.

      – Neil Barnwell
      Mar 8 at 17:31
















    I used the constructor for pass the Id 'Person(Crud.Id)'

    – Amadeu Antunes
    Mar 8 at 17:26






    I used the constructor for pass the Id 'Person(Crud.Id)'

    – Amadeu Antunes
    Mar 8 at 17:26














    if you check my class Person you will see the constructor

    – Amadeu Antunes
    Mar 8 at 17:27





    if you check my class Person you will see the constructor

    – Amadeu Antunes
    Mar 8 at 17:27













    public Person(int _id) Id = _id;

    – Amadeu Antunes
    Mar 8 at 17:28





    public Person(int _id) Id = _id;

    – Amadeu Antunes
    Mar 8 at 17:28













    Yeah I'm literally suggesting that the ID is set by something closer to the database, therefore is not a requirement to initialise a new Person, therefore shouldn't be part of the constructor. If you don't want to modify your design you're going to struggle to solve your problem.

    – Neil Barnwell
    Mar 8 at 17:30





    Yeah I'm literally suggesting that the ID is set by something closer to the database, therefore is not a requirement to initialise a new Person, therefore shouldn't be part of the constructor. If you don't want to modify your design you're going to struggle to solve your problem.

    – Neil Barnwell
    Mar 8 at 17:30




    2




    2





    In fact what you should be doing really is using an ORM where this is all a solved problem, and leaves you do get on with solving unsolved problems in your business. Unless this is a homework question, I suppose.

    – Neil Barnwell
    Mar 8 at 17:31





    In fact what you should be doing really is using an ORM where this is all a solved problem, and leaves you do get on with solving unsolved problems in your business. Unless this is a homework question, I suppose.

    – Neil Barnwell
    Mar 8 at 17:31













    1














    public MessageError Update(T t)

    /* I used this why to the the property in my last version I get the name of property by Parameter */
    var type = t.GetType();
    PropertyInfo prop = type.GetProperty("Id");

    var value = prop.GetValue(t);
    List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
    List.Add(t);
    return new MessageError

    Status = Status.Sucessful
    ;






    share|improve this answer



























      1














      public MessageError Update(T t)

      /* I used this why to the the property in my last version I get the name of property by Parameter */
      var type = t.GetType();
      PropertyInfo prop = type.GetProperty("Id");

      var value = prop.GetValue(t);
      List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
      List.Add(t);
      return new MessageError

      Status = Status.Sucessful
      ;






      share|improve this answer

























        1












        1








        1







        public MessageError Update(T t)

        /* I used this why to the the property in my last version I get the name of property by Parameter */
        var type = t.GetType();
        PropertyInfo prop = type.GetProperty("Id");

        var value = prop.GetValue(t);
        List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
        List.Add(t);
        return new MessageError

        Status = Status.Sucessful
        ;






        share|improve this answer













        public MessageError Update(T t)

        /* I used this why to the the property in my last version I get the name of property by Parameter */
        var type = t.GetType();
        PropertyInfo prop = type.GetProperty("Id");

        var value = prop.GetValue(t);
        List.RemoveAll(x => x.GetType().GetProperty("Id").GetValue(x) == value);
        List.Add(t);
        return new MessageError

        Status = Status.Sucessful
        ;







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 18:00









        Amadeu AntunesAmadeu Antunes

        457526




        457526



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51826712%2fhow-can-get-property-and-the-value-in-a-generic-class%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived