Generic solution to add new property to existing class

Hi

I have a C # class which is a third party reference in my console app.

Am looking for some generic solution to add a new property to the existing C# class.

Eg: I have a customer class with Name, Age, and Title. This class I got from the third party and now I need to add new property say the address. So similarly I should be able to add any new property.

Let me know any pointers on this.
Srinivasan BaskaranTechnology ArchitectAsked:
Who is Participating?
 
Éric MoreauConnect With a Mentor Senior .Net ConsultantCommented:
if the class is not sealed, you can inherit from it in a new class and add your own properties.
0
 
MishaConnect With a Mentor ProgrammerCommented:
There is article about building C# objects dynamically
https://www.oreilly.com/learning/building-c-objects-dynamically
0
 
it_saigeConnect With a Mentor DeveloperCommented:
*NO POINTS*

What Eric is saying is this:
using System;

namespace EE_Q29097252
{
	class Program
	{
		static void Main(string[] args)
		{
			var implementation = new MyClass { ID = 1, Name = "My Class", BirthDate = DateTime.Now.AddYears(-30) };
			Console.WriteLine(implementation);
			Console.ReadLine();
		}
	}

	class MyClass : SomeThirdPartyClass
	{
		public DateTime BirthDate { get; set; }
		public override string ToString()
		{
			return $"{{ ID: {ID}, Name: {Name}, BirthDate: {BirthDate.ToShortDateString()} }}";
		}
	}

	class SomeThirdPartyClass
	{
		public int ID { get; set; }
		public string Name { get; set; }
	}
}

Open in new window

Which produces the following output -Capture.PNG-saige-
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Chris StanyonConnect With a Mentor Commented:
This is very common in all OOP languages and it's known as Inheritance. It's actually one of the 4 key principles of Object Oriented Programming. A solid understanding of this is pretty crucial to OOP programming, so it may be worth reading up on it. @Saige has already shown you the code to do this - the important part is the class definition:

class NewClass : BaseClass { }

This will create a NewClass that inherits the members of the BaseClass. Depending on the BaseClass, you can then add your own members (properties/methods etc) and override existing members.
0
 
it_saigeConnect With a Mentor DeveloperCommented:
Just to add add though, as Eric stated, this is if and only if the class you are inheriting from is not sealed.

Otherwise you will nee to use another method known as property mapping, whereby you create a new class that can be implicitly or explicitly converted from the baseclass to your new class.

-saige-
0
 
Éric MoreauSenior .Net ConsultantCommented:
And BTW, don't expect the base class to do all the selects/inserts/updates/deletes for you because the base class knows nothing about your new properties.
0
 
it_saigeConnect With a Mentor DeveloperCommented:
Here is an example implementation of property mapping:
using System;

namespace EE_Q29097252
{
	class Program
	{
		static void Main(string[] args)
		{
			var implementation = (MyClass)new SomeThirdPartyClass { ID = 1, Name = "My Class" };
			implementation.BirthDate = DateTime.Now.AddYears(-30);
			Console.WriteLine(implementation);
			Console.ReadLine();
		}
	}

	class MyClass
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime BirthDate { get; set; }

		public static explicit operator MyClass(SomeThirdPartyClass source)
		{
			return new MyClass { ID = source.ID, Name = source.Name };
		}

		public override string ToString()
		{
			return $"{{ ID: {ID}, Name: {Name}, BirthDate: {BirthDate.ToShortDateString()} }}";
		}
	}

	sealed class SomeThirdPartyClass
	{
		public int ID { get; set; }
		public string Name { get; set; }
	}
}

Open in new window

Which produces the same output as above.

-saige-
0
 
it_saigeConnect With a Mentor DeveloperCommented:
And in case you don't want to use operator overloads in all of your classes, here is another example of property mapping which uses reflection and generics (I used this in a previous EE_PAQ):
using System;
using System.Reflection;

namespace EE_Q29097252
{
	class Program
	{
		static void Main(string[] args)
		{
			var implementation = new SomeThirdPartyClass { ID = 1, Name = "My Class" }.CopyTo(new MyClass());
			implementation.BirthDate = DateTime.Now.AddYears(-30);
			Console.WriteLine(implementation);
			Console.ReadLine();
		}
	}

	class MyClass
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime BirthDate { get; set; }

		public override string ToString()
		{
			return $"{{ ID: {ID}, Name: {Name}, BirthDate: {BirthDate.ToShortDateString()} }}";
		}
	}

	sealed class SomeThirdPartyClass
	{
		public int ID { get; set; }
		public string Name { get; set; }
	}

	static class Extensions
	{
		public static T CopyTo<S, T>(this S source, T target) where T : class, new()
		{
			foreach (var s_prop in typeof(S).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
			{
				var t_prop = typeof(T).GetProperty(s_prop.Name);
				if (t_prop != null && t_prop.CanWrite)
				{
					try
					{
						t_prop.SetValue(target, s_prop.GetValue(source, null));
					}
					catch (Exception)
					{
						// There was a problem setting the value of the property
						// in the target object.  Log it, handle it or both.
					}
				}
			}
			return target;
		}
	}
}

Open in new window

Which also produces the same output as previously shown.

-saige-
0
 
Srinivasan BaskaranTechnology ArchitectAuthor Commented:
Got my idea validated plus multiple other options which i was not aware of it. Thanks to all who have contributed to my query.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.