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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MishaProgrammerCommented:
There is article about building C# objects dynamically
https://www.oreilly.com/learning/building-c-objects-dynamically
0
Éric MoreauSenior .Net ConsultantCommented:
if the class is not sealed, you can inherit from it in a new class and add your own properties.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
*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
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Chris StanyonWebDevCommented:
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_saigeDeveloperCommented:
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_saigeDeveloperCommented:
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_saigeDeveloperCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Best Practice

From novice to tech pro — start learning today.