cast class into another class or convert class to another
my question is shown in this code
I have class like that
public class maincs
{
public int a;
public int b;
public int c;
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
public void methoda (sub1 model)
{
maincs mdata = new maincs(){a = model.a , b = model.b , c= model.c} ;
// is there is a way to directly cast class sub1 into main like that
mdata = (maincs) model;
}
c# casting class type-conversion
add a comment |
my question is shown in this code
I have class like that
public class maincs
{
public int a;
public int b;
public int c;
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
public void methoda (sub1 model)
{
maincs mdata = new maincs(){a = model.a , b = model.b , c= model.c} ;
// is there is a way to directly cast class sub1 into main like that
mdata = (maincs) model;
}
c# casting class type-conversion
1
This code doesn't make sense. Post code that compiles (it's not the cast that's the problem).
– µBio
Sep 8 '10 at 23:46
9
Quite harsh.. Missing aclass
keyword doesnt take the sense away.
– nawfal
Jan 16 '14 at 4:56
There are existing lightweight mapper libraries written already for exactly this purpose. They handle a lot more edge cases. You can google it.
– nawfal
Jan 16 '14 at 5:15
First and easy solution: automapper.org
– Soren
May 14 '14 at 9:08
add a comment |
my question is shown in this code
I have class like that
public class maincs
{
public int a;
public int b;
public int c;
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
public void methoda (sub1 model)
{
maincs mdata = new maincs(){a = model.a , b = model.b , c= model.c} ;
// is there is a way to directly cast class sub1 into main like that
mdata = (maincs) model;
}
c# casting class type-conversion
my question is shown in this code
I have class like that
public class maincs
{
public int a;
public int b;
public int c;
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
public void methoda (sub1 model)
{
maincs mdata = new maincs(){a = model.a , b = model.b , c= model.c} ;
// is there is a way to directly cast class sub1 into main like that
mdata = (maincs) model;
}
c# casting class type-conversion
c# casting class type-conversion
edited Sep 15 '16 at 9:31
Dor Cohen
10.6k1867142
10.6k1867142
asked Sep 8 '10 at 23:40
Khalid OmarKhalid Omar
1,10852342
1,10852342
1
This code doesn't make sense. Post code that compiles (it's not the cast that's the problem).
– µBio
Sep 8 '10 at 23:46
9
Quite harsh.. Missing aclass
keyword doesnt take the sense away.
– nawfal
Jan 16 '14 at 4:56
There are existing lightweight mapper libraries written already for exactly this purpose. They handle a lot more edge cases. You can google it.
– nawfal
Jan 16 '14 at 5:15
First and easy solution: automapper.org
– Soren
May 14 '14 at 9:08
add a comment |
1
This code doesn't make sense. Post code that compiles (it's not the cast that's the problem).
– µBio
Sep 8 '10 at 23:46
9
Quite harsh.. Missing aclass
keyword doesnt take the sense away.
– nawfal
Jan 16 '14 at 4:56
There are existing lightweight mapper libraries written already for exactly this purpose. They handle a lot more edge cases. You can google it.
– nawfal
Jan 16 '14 at 5:15
First and easy solution: automapper.org
– Soren
May 14 '14 at 9:08
1
1
This code doesn't make sense. Post code that compiles (it's not the cast that's the problem).
– µBio
Sep 8 '10 at 23:46
This code doesn't make sense. Post code that compiles (it's not the cast that's the problem).
– µBio
Sep 8 '10 at 23:46
9
9
Quite harsh.. Missing a
class
keyword doesnt take the sense away.– nawfal
Jan 16 '14 at 4:56
Quite harsh.. Missing a
class
keyword doesnt take the sense away.– nawfal
Jan 16 '14 at 4:56
There are existing lightweight mapper libraries written already for exactly this purpose. They handle a lot more edge cases. You can google it.
– nawfal
Jan 16 '14 at 5:15
There are existing lightweight mapper libraries written already for exactly this purpose. They handle a lot more edge cases. You can google it.
– nawfal
Jan 16 '14 at 5:15
First and easy solution: automapper.org
– Soren
May 14 '14 at 9:08
First and easy solution: automapper.org
– Soren
May 14 '14 at 9:08
add a comment |
9 Answers
9
active
oldest
votes
What he wants to say is:
"If you have two classes which share most of the same properties you can cast an object from class a
to class b
and automatically make the system understand the assignment via the shared property names?"
Option 1: Use reflection
Disadvantage : It's gonna slow you down more than you think.
Option 2: Make one class derive from another, the first one with common properties and other an extension of that.
Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!
Let there be:
class customer
{
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
}
class employee
{
public string firstname { get; set; }
public int age { get; set; }
}
Now here is an extension for Object type:
public static T Cast<T>(this Object myobj)
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source ;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
propertyInfo.SetValue(x,value,null);
}
return (T)x;
}
Now you use it like this:
static void Main(string args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
Method cast checks common properties between two objects and does the assignment automatically.
1
That what i mean exactly
– Khalid Omar
Sep 9 '10 at 1:54
Nice solution, but as you said, overhead and complexity :)
– Noctis
Apr 14 '14 at 0:19
I guess you have missed to make use of 'z' variable. It should be used when initializing 'members' var i.e. List<MemberInfo> members = z.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList();
– Aamol
Feb 27 '17 at 23:09
2
The extension method Cast will cause conflict with System.Linq Enumerable.Cast<TResult> and could result in an error that is hard to debug. Changing the name is recommended.
– usefulBee
Jan 16 '18 at 15:47
add a comment |
You have already defined the conversion, you just need to take it one step further if you would like to be able to cast. For example:
public class sub1
{
public int a;
public int b;
public int c;
public static explicit operator maincs(sub1 obj)
{
maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c };
return output;
}
}
Which then allows you to do something like
static void Main()
{
sub1 mySub = new sub1();
maincs myMain = (maincs)mySub;
}
3
Even better than the selected answer
– Noctis
Apr 14 '14 at 0:19
1
Great answer. Thanks.
– Ellis
Dec 22 '15 at 14:39
Are there any implications for converting/casting from one class to another with the exact props using your code?
– Code
Apr 5 '17 at 7:36
add a comment |
Use JSON serialization and deserialization:
using Newtonsoft.Json;
Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
Or:
public class Class1
{
public static explicit operator Class2(Class1 obj)
{
return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
}
}
Which then allows you to do something like
static void Main()
{
Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;
}
1
Yes, using Newtonsoft json serializer is quite simple and efficient. There is .Net serializer but I found Newtonsoft do well over .Net json serializer. I found this link which gives a brief comparision newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm
– Aamol
Feb 28 '17 at 0:38
1
this seemed latest and worked best for my needs. upvoted!
– Puerto
Jun 12 '18 at 13:03
add a comment |
You could change your class structure to:
public class maincs : sub1
{
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
Then you could keep a list of sub1 and cast some of them to mainc.
This doesn't compile either. Maybe you forgot theclass
keyword
– Carlos Muñoz
Sep 8 '10 at 23:48
Oops, that's what I get for copy/paste.
– Jake Pearson
Sep 9 '10 at 2:04
add a comment |
You can provide an explicit overload for the cast operator:
public static explicit operator maincs(sub1 val)
{
var ret = new maincs() { a = val.a, b = val.b, c = val.c };
return ret;
}
Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.
add a comment |
By using following code you can copy any class object to another class object for same name and same type of properties.
public class CopyClass
{
/// <summary>
/// Copy an object to destination object, only matching fields will be copied
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceObject">An object with matching fields of the destination object</param>
/// <param name="destObject">Destination object, must already be created</param>
public static void CopyObject<T>(object sourceObject, ref T destObject)
{
// If either the source, or destination is null, return
if (sourceObject == null || destObject == null)
return;
// Get the type of each object
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();
// Loop through the source properties
foreach (PropertyInfo p in sourceType.GetProperties())
{
// Get the matching property in the destination object
PropertyInfo targetObj = targetType.GetProperty(p.Name);
// If there is none, skip
if (targetObj == null)
continue;
// Set the value in the destination
targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
}
}
}
Call Method Like,
ClassA objA = new ClassA();
ClassB objB = new ClassB();
CopyClass.CopyObject(objOfferMast, ref objB);
It will copy objA
into objB
.
1
Please be aware that if you're using this solution, you might run into issues when classes have the same name for properties, but with different types. For example:public class A { public int Age{get;set;}}
andpublic class B { public string Age{get;set;}}
Will throw an exception, if you're trying to convert fromA
toB
– Noctis
Apr 14 '14 at 0:32
This type of conversion could also lead to some huge performance issues. Use it carefully and certainly not in for-loops
– RPDeshaies
Jun 16 '15 at 14:55
add a comment |
There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.
In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.
public static T Transform<T>(this object myobj, string excludeFields = null)
{
// Compose a list of unwanted members
if (string.IsNullOrWhiteSpace(excludeFields))
excludeFields = string.Empty;
excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";
var objectType = myobj.GetType();
var targetType = typeof(T);
var targetInstance = Activator.CreateInstance(targetType, false);
// Find common members by name
var sourceMembers = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var targetMembers = from source in targetType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
// Remove unwanted members
commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));
foreach (var memberInfo in commonMembers)
{
if (!((PropertyInfo)memberInfo).CanWrite) continue;
var targetProperty = typeof(T).GetProperty(memberInfo.Name);
if (targetProperty == null) continue;
var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
if (sourceProperty == null) continue;
// Check source and target types are the same
if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;
var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
if (value == null) continue;
// Set the value
targetProperty.SetValue(targetInstance, value, null);
}
return (T)targetInstance;
}
that will work as long as you dont have ENUMS in your object as properties
– Natalia Z
Jun 29 '18 at 15:28
add a comment |
Using this code you can copy any class object to another class object for same name and same type of properties.
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);
add a comment |
var obj = _account.Retrieve(Email, hash);
AccountInfoResponse accountInfoResponse = new AccountInfoResponse();
if (obj != null)
{
accountInfoResponse =
JsonConvert.
DeserializeObject<AccountInfoResponse>
(JsonConvert.SerializeObject(obj));
}
image description
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3672742%2fcast-class-into-another-class-or-convert-class-to-another%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
What he wants to say is:
"If you have two classes which share most of the same properties you can cast an object from class a
to class b
and automatically make the system understand the assignment via the shared property names?"
Option 1: Use reflection
Disadvantage : It's gonna slow you down more than you think.
Option 2: Make one class derive from another, the first one with common properties and other an extension of that.
Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!
Let there be:
class customer
{
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
}
class employee
{
public string firstname { get; set; }
public int age { get; set; }
}
Now here is an extension for Object type:
public static T Cast<T>(this Object myobj)
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source ;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
propertyInfo.SetValue(x,value,null);
}
return (T)x;
}
Now you use it like this:
static void Main(string args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
Method cast checks common properties between two objects and does the assignment automatically.
1
That what i mean exactly
– Khalid Omar
Sep 9 '10 at 1:54
Nice solution, but as you said, overhead and complexity :)
– Noctis
Apr 14 '14 at 0:19
I guess you have missed to make use of 'z' variable. It should be used when initializing 'members' var i.e. List<MemberInfo> members = z.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList();
– Aamol
Feb 27 '17 at 23:09
2
The extension method Cast will cause conflict with System.Linq Enumerable.Cast<TResult> and could result in an error that is hard to debug. Changing the name is recommended.
– usefulBee
Jan 16 '18 at 15:47
add a comment |
What he wants to say is:
"If you have two classes which share most of the same properties you can cast an object from class a
to class b
and automatically make the system understand the assignment via the shared property names?"
Option 1: Use reflection
Disadvantage : It's gonna slow you down more than you think.
Option 2: Make one class derive from another, the first one with common properties and other an extension of that.
Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!
Let there be:
class customer
{
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
}
class employee
{
public string firstname { get; set; }
public int age { get; set; }
}
Now here is an extension for Object type:
public static T Cast<T>(this Object myobj)
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source ;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
propertyInfo.SetValue(x,value,null);
}
return (T)x;
}
Now you use it like this:
static void Main(string args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
Method cast checks common properties between two objects and does the assignment automatically.
1
That what i mean exactly
– Khalid Omar
Sep 9 '10 at 1:54
Nice solution, but as you said, overhead and complexity :)
– Noctis
Apr 14 '14 at 0:19
I guess you have missed to make use of 'z' variable. It should be used when initializing 'members' var i.e. List<MemberInfo> members = z.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList();
– Aamol
Feb 27 '17 at 23:09
2
The extension method Cast will cause conflict with System.Linq Enumerable.Cast<TResult> and could result in an error that is hard to debug. Changing the name is recommended.
– usefulBee
Jan 16 '18 at 15:47
add a comment |
What he wants to say is:
"If you have two classes which share most of the same properties you can cast an object from class a
to class b
and automatically make the system understand the assignment via the shared property names?"
Option 1: Use reflection
Disadvantage : It's gonna slow you down more than you think.
Option 2: Make one class derive from another, the first one with common properties and other an extension of that.
Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!
Let there be:
class customer
{
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
}
class employee
{
public string firstname { get; set; }
public int age { get; set; }
}
Now here is an extension for Object type:
public static T Cast<T>(this Object myobj)
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source ;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
propertyInfo.SetValue(x,value,null);
}
return (T)x;
}
Now you use it like this:
static void Main(string args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
Method cast checks common properties between two objects and does the assignment automatically.
What he wants to say is:
"If you have two classes which share most of the same properties you can cast an object from class a
to class b
and automatically make the system understand the assignment via the shared property names?"
Option 1: Use reflection
Disadvantage : It's gonna slow you down more than you think.
Option 2: Make one class derive from another, the first one with common properties and other an extension of that.
Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!
Let there be:
class customer
{
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
}
class employee
{
public string firstname { get; set; }
public int age { get; set; }
}
Now here is an extension for Object type:
public static T Cast<T>(this Object myobj)
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source ;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
propertyInfo.SetValue(x,value,null);
}
return (T)x;
}
Now you use it like this:
static void Main(string args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
Method cast checks common properties between two objects and does the assignment automatically.
edited Dec 22 '15 at 15:34
Ellis
13813
13813
answered Sep 9 '10 at 1:42
StackerStacker
4,3161565123
4,3161565123
1
That what i mean exactly
– Khalid Omar
Sep 9 '10 at 1:54
Nice solution, but as you said, overhead and complexity :)
– Noctis
Apr 14 '14 at 0:19
I guess you have missed to make use of 'z' variable. It should be used when initializing 'members' var i.e. List<MemberInfo> members = z.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList();
– Aamol
Feb 27 '17 at 23:09
2
The extension method Cast will cause conflict with System.Linq Enumerable.Cast<TResult> and could result in an error that is hard to debug. Changing the name is recommended.
– usefulBee
Jan 16 '18 at 15:47
add a comment |
1
That what i mean exactly
– Khalid Omar
Sep 9 '10 at 1:54
Nice solution, but as you said, overhead and complexity :)
– Noctis
Apr 14 '14 at 0:19
I guess you have missed to make use of 'z' variable. It should be used when initializing 'members' var i.e. List<MemberInfo> members = z.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList();
– Aamol
Feb 27 '17 at 23:09
2
The extension method Cast will cause conflict with System.Linq Enumerable.Cast<TResult> and could result in an error that is hard to debug. Changing the name is recommended.
– usefulBee
Jan 16 '18 at 15:47
1
1
That what i mean exactly
– Khalid Omar
Sep 9 '10 at 1:54
That what i mean exactly
– Khalid Omar
Sep 9 '10 at 1:54
Nice solution, but as you said, overhead and complexity :)
– Noctis
Apr 14 '14 at 0:19
Nice solution, but as you said, overhead and complexity :)
– Noctis
Apr 14 '14 at 0:19
I guess you have missed to make use of 'z' variable. It should be used when initializing 'members' var i.e. List<MemberInfo> members = z.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList();
– Aamol
Feb 27 '17 at 23:09
I guess you have missed to make use of 'z' variable. It should be used when initializing 'members' var i.e. List<MemberInfo> members = z.Where(memberInfo => d.Select(c => c.Name) .ToList().Contains(memberInfo.Name)).ToList();
– Aamol
Feb 27 '17 at 23:09
2
2
The extension method Cast will cause conflict with System.Linq Enumerable.Cast<TResult> and could result in an error that is hard to debug. Changing the name is recommended.
– usefulBee
Jan 16 '18 at 15:47
The extension method Cast will cause conflict with System.Linq Enumerable.Cast<TResult> and could result in an error that is hard to debug. Changing the name is recommended.
– usefulBee
Jan 16 '18 at 15:47
add a comment |
You have already defined the conversion, you just need to take it one step further if you would like to be able to cast. For example:
public class sub1
{
public int a;
public int b;
public int c;
public static explicit operator maincs(sub1 obj)
{
maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c };
return output;
}
}
Which then allows you to do something like
static void Main()
{
sub1 mySub = new sub1();
maincs myMain = (maincs)mySub;
}
3
Even better than the selected answer
– Noctis
Apr 14 '14 at 0:19
1
Great answer. Thanks.
– Ellis
Dec 22 '15 at 14:39
Are there any implications for converting/casting from one class to another with the exact props using your code?
– Code
Apr 5 '17 at 7:36
add a comment |
You have already defined the conversion, you just need to take it one step further if you would like to be able to cast. For example:
public class sub1
{
public int a;
public int b;
public int c;
public static explicit operator maincs(sub1 obj)
{
maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c };
return output;
}
}
Which then allows you to do something like
static void Main()
{
sub1 mySub = new sub1();
maincs myMain = (maincs)mySub;
}
3
Even better than the selected answer
– Noctis
Apr 14 '14 at 0:19
1
Great answer. Thanks.
– Ellis
Dec 22 '15 at 14:39
Are there any implications for converting/casting from one class to another with the exact props using your code?
– Code
Apr 5 '17 at 7:36
add a comment |
You have already defined the conversion, you just need to take it one step further if you would like to be able to cast. For example:
public class sub1
{
public int a;
public int b;
public int c;
public static explicit operator maincs(sub1 obj)
{
maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c };
return output;
}
}
Which then allows you to do something like
static void Main()
{
sub1 mySub = new sub1();
maincs myMain = (maincs)mySub;
}
You have already defined the conversion, you just need to take it one step further if you would like to be able to cast. For example:
public class sub1
{
public int a;
public int b;
public int c;
public static explicit operator maincs(sub1 obj)
{
maincs output = new maincs() { a = obj.a, b = obj.b, c = obj.c };
return output;
}
}
Which then allows you to do something like
static void Main()
{
sub1 mySub = new sub1();
maincs myMain = (maincs)mySub;
}
answered Sep 8 '10 at 23:48
Anthony PegramAnthony Pegram
99.5k22193231
99.5k22193231
3
Even better than the selected answer
– Noctis
Apr 14 '14 at 0:19
1
Great answer. Thanks.
– Ellis
Dec 22 '15 at 14:39
Are there any implications for converting/casting from one class to another with the exact props using your code?
– Code
Apr 5 '17 at 7:36
add a comment |
3
Even better than the selected answer
– Noctis
Apr 14 '14 at 0:19
1
Great answer. Thanks.
– Ellis
Dec 22 '15 at 14:39
Are there any implications for converting/casting from one class to another with the exact props using your code?
– Code
Apr 5 '17 at 7:36
3
3
Even better than the selected answer
– Noctis
Apr 14 '14 at 0:19
Even better than the selected answer
– Noctis
Apr 14 '14 at 0:19
1
1
Great answer. Thanks.
– Ellis
Dec 22 '15 at 14:39
Great answer. Thanks.
– Ellis
Dec 22 '15 at 14:39
Are there any implications for converting/casting from one class to another with the exact props using your code?
– Code
Apr 5 '17 at 7:36
Are there any implications for converting/casting from one class to another with the exact props using your code?
– Code
Apr 5 '17 at 7:36
add a comment |
Use JSON serialization and deserialization:
using Newtonsoft.Json;
Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
Or:
public class Class1
{
public static explicit operator Class2(Class1 obj)
{
return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
}
}
Which then allows you to do something like
static void Main()
{
Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;
}
1
Yes, using Newtonsoft json serializer is quite simple and efficient. There is .Net serializer but I found Newtonsoft do well over .Net json serializer. I found this link which gives a brief comparision newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm
– Aamol
Feb 28 '17 at 0:38
1
this seemed latest and worked best for my needs. upvoted!
– Puerto
Jun 12 '18 at 13:03
add a comment |
Use JSON serialization and deserialization:
using Newtonsoft.Json;
Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
Or:
public class Class1
{
public static explicit operator Class2(Class1 obj)
{
return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
}
}
Which then allows you to do something like
static void Main()
{
Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;
}
1
Yes, using Newtonsoft json serializer is quite simple and efficient. There is .Net serializer but I found Newtonsoft do well over .Net json serializer. I found this link which gives a brief comparision newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm
– Aamol
Feb 28 '17 at 0:38
1
this seemed latest and worked best for my needs. upvoted!
– Puerto
Jun 12 '18 at 13:03
add a comment |
Use JSON serialization and deserialization:
using Newtonsoft.Json;
Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
Or:
public class Class1
{
public static explicit operator Class2(Class1 obj)
{
return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
}
}
Which then allows you to do something like
static void Main()
{
Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;
}
Use JSON serialization and deserialization:
using Newtonsoft.Json;
Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
Or:
public class Class1
{
public static explicit operator Class2(Class1 obj)
{
return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
}
}
Which then allows you to do something like
static void Main()
{
Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;
}
edited May 9 '18 at 12:58
answered Jul 22 '16 at 5:45
Tyler LongTyler Long
10.9k67065
10.9k67065
1
Yes, using Newtonsoft json serializer is quite simple and efficient. There is .Net serializer but I found Newtonsoft do well over .Net json serializer. I found this link which gives a brief comparision newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm
– Aamol
Feb 28 '17 at 0:38
1
this seemed latest and worked best for my needs. upvoted!
– Puerto
Jun 12 '18 at 13:03
add a comment |
1
Yes, using Newtonsoft json serializer is quite simple and efficient. There is .Net serializer but I found Newtonsoft do well over .Net json serializer. I found this link which gives a brief comparision newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm
– Aamol
Feb 28 '17 at 0:38
1
this seemed latest and worked best for my needs. upvoted!
– Puerto
Jun 12 '18 at 13:03
1
1
Yes, using Newtonsoft json serializer is quite simple and efficient. There is .Net serializer but I found Newtonsoft do well over .Net json serializer. I found this link which gives a brief comparision newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm
– Aamol
Feb 28 '17 at 0:38
Yes, using Newtonsoft json serializer is quite simple and efficient. There is .Net serializer but I found Newtonsoft do well over .Net json serializer. I found this link which gives a brief comparision newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm
– Aamol
Feb 28 '17 at 0:38
1
1
this seemed latest and worked best for my needs. upvoted!
– Puerto
Jun 12 '18 at 13:03
this seemed latest and worked best for my needs. upvoted!
– Puerto
Jun 12 '18 at 13:03
add a comment |
You could change your class structure to:
public class maincs : sub1
{
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
Then you could keep a list of sub1 and cast some of them to mainc.
This doesn't compile either. Maybe you forgot theclass
keyword
– Carlos Muñoz
Sep 8 '10 at 23:48
Oops, that's what I get for copy/paste.
– Jake Pearson
Sep 9 '10 at 2:04
add a comment |
You could change your class structure to:
public class maincs : sub1
{
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
Then you could keep a list of sub1 and cast some of them to mainc.
This doesn't compile either. Maybe you forgot theclass
keyword
– Carlos Muñoz
Sep 8 '10 at 23:48
Oops, that's what I get for copy/paste.
– Jake Pearson
Sep 9 '10 at 2:04
add a comment |
You could change your class structure to:
public class maincs : sub1
{
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
Then you could keep a list of sub1 and cast some of them to mainc.
You could change your class structure to:
public class maincs : sub1
{
public int d;
}
public class sub1
{
public int a;
public int b;
public int c;
}
Then you could keep a list of sub1 and cast some of them to mainc.
edited Sep 9 '10 at 2:04
answered Sep 8 '10 at 23:46
Jake PearsonJake Pearson
18k86388
18k86388
This doesn't compile either. Maybe you forgot theclass
keyword
– Carlos Muñoz
Sep 8 '10 at 23:48
Oops, that's what I get for copy/paste.
– Jake Pearson
Sep 9 '10 at 2:04
add a comment |
This doesn't compile either. Maybe you forgot theclass
keyword
– Carlos Muñoz
Sep 8 '10 at 23:48
Oops, that's what I get for copy/paste.
– Jake Pearson
Sep 9 '10 at 2:04
This doesn't compile either. Maybe you forgot the
class
keyword– Carlos Muñoz
Sep 8 '10 at 23:48
This doesn't compile either. Maybe you forgot the
class
keyword– Carlos Muñoz
Sep 8 '10 at 23:48
Oops, that's what I get for copy/paste.
– Jake Pearson
Sep 9 '10 at 2:04
Oops, that's what I get for copy/paste.
– Jake Pearson
Sep 9 '10 at 2:04
add a comment |
You can provide an explicit overload for the cast operator:
public static explicit operator maincs(sub1 val)
{
var ret = new maincs() { a = val.a, b = val.b, c = val.c };
return ret;
}
Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.
add a comment |
You can provide an explicit overload for the cast operator:
public static explicit operator maincs(sub1 val)
{
var ret = new maincs() { a = val.a, b = val.b, c = val.c };
return ret;
}
Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.
add a comment |
You can provide an explicit overload for the cast operator:
public static explicit operator maincs(sub1 val)
{
var ret = new maincs() { a = val.a, b = val.b, c = val.c };
return ret;
}
Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.
You can provide an explicit overload for the cast operator:
public static explicit operator maincs(sub1 val)
{
var ret = new maincs() { a = val.a, b = val.b, c = val.c };
return ret;
}
Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.
answered Sep 8 '10 at 23:50
Chris ShafferChris Shaffer
28.5k44160
28.5k44160
add a comment |
add a comment |
By using following code you can copy any class object to another class object for same name and same type of properties.
public class CopyClass
{
/// <summary>
/// Copy an object to destination object, only matching fields will be copied
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceObject">An object with matching fields of the destination object</param>
/// <param name="destObject">Destination object, must already be created</param>
public static void CopyObject<T>(object sourceObject, ref T destObject)
{
// If either the source, or destination is null, return
if (sourceObject == null || destObject == null)
return;
// Get the type of each object
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();
// Loop through the source properties
foreach (PropertyInfo p in sourceType.GetProperties())
{
// Get the matching property in the destination object
PropertyInfo targetObj = targetType.GetProperty(p.Name);
// If there is none, skip
if (targetObj == null)
continue;
// Set the value in the destination
targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
}
}
}
Call Method Like,
ClassA objA = new ClassA();
ClassB objB = new ClassB();
CopyClass.CopyObject(objOfferMast, ref objB);
It will copy objA
into objB
.
1
Please be aware that if you're using this solution, you might run into issues when classes have the same name for properties, but with different types. For example:public class A { public int Age{get;set;}}
andpublic class B { public string Age{get;set;}}
Will throw an exception, if you're trying to convert fromA
toB
– Noctis
Apr 14 '14 at 0:32
This type of conversion could also lead to some huge performance issues. Use it carefully and certainly not in for-loops
– RPDeshaies
Jun 16 '15 at 14:55
add a comment |
By using following code you can copy any class object to another class object for same name and same type of properties.
public class CopyClass
{
/// <summary>
/// Copy an object to destination object, only matching fields will be copied
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceObject">An object with matching fields of the destination object</param>
/// <param name="destObject">Destination object, must already be created</param>
public static void CopyObject<T>(object sourceObject, ref T destObject)
{
// If either the source, or destination is null, return
if (sourceObject == null || destObject == null)
return;
// Get the type of each object
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();
// Loop through the source properties
foreach (PropertyInfo p in sourceType.GetProperties())
{
// Get the matching property in the destination object
PropertyInfo targetObj = targetType.GetProperty(p.Name);
// If there is none, skip
if (targetObj == null)
continue;
// Set the value in the destination
targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
}
}
}
Call Method Like,
ClassA objA = new ClassA();
ClassB objB = new ClassB();
CopyClass.CopyObject(objOfferMast, ref objB);
It will copy objA
into objB
.
1
Please be aware that if you're using this solution, you might run into issues when classes have the same name for properties, but with different types. For example:public class A { public int Age{get;set;}}
andpublic class B { public string Age{get;set;}}
Will throw an exception, if you're trying to convert fromA
toB
– Noctis
Apr 14 '14 at 0:32
This type of conversion could also lead to some huge performance issues. Use it carefully and certainly not in for-loops
– RPDeshaies
Jun 16 '15 at 14:55
add a comment |
By using following code you can copy any class object to another class object for same name and same type of properties.
public class CopyClass
{
/// <summary>
/// Copy an object to destination object, only matching fields will be copied
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceObject">An object with matching fields of the destination object</param>
/// <param name="destObject">Destination object, must already be created</param>
public static void CopyObject<T>(object sourceObject, ref T destObject)
{
// If either the source, or destination is null, return
if (sourceObject == null || destObject == null)
return;
// Get the type of each object
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();
// Loop through the source properties
foreach (PropertyInfo p in sourceType.GetProperties())
{
// Get the matching property in the destination object
PropertyInfo targetObj = targetType.GetProperty(p.Name);
// If there is none, skip
if (targetObj == null)
continue;
// Set the value in the destination
targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
}
}
}
Call Method Like,
ClassA objA = new ClassA();
ClassB objB = new ClassB();
CopyClass.CopyObject(objOfferMast, ref objB);
It will copy objA
into objB
.
By using following code you can copy any class object to another class object for same name and same type of properties.
public class CopyClass
{
/// <summary>
/// Copy an object to destination object, only matching fields will be copied
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceObject">An object with matching fields of the destination object</param>
/// <param name="destObject">Destination object, must already be created</param>
public static void CopyObject<T>(object sourceObject, ref T destObject)
{
// If either the source, or destination is null, return
if (sourceObject == null || destObject == null)
return;
// Get the type of each object
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();
// Loop through the source properties
foreach (PropertyInfo p in sourceType.GetProperties())
{
// Get the matching property in the destination object
PropertyInfo targetObj = targetType.GetProperty(p.Name);
// If there is none, skip
if (targetObj == null)
continue;
// Set the value in the destination
targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
}
}
}
Call Method Like,
ClassA objA = new ClassA();
ClassB objB = new ClassB();
CopyClass.CopyObject(objOfferMast, ref objB);
It will copy objA
into objB
.
edited Jan 16 '14 at 4:59
nawfal
43.6k36257304
43.6k36257304
answered Oct 4 '13 at 6:31
Kailas ManeKailas Mane
1,43211211
1,43211211
1
Please be aware that if you're using this solution, you might run into issues when classes have the same name for properties, but with different types. For example:public class A { public int Age{get;set;}}
andpublic class B { public string Age{get;set;}}
Will throw an exception, if you're trying to convert fromA
toB
– Noctis
Apr 14 '14 at 0:32
This type of conversion could also lead to some huge performance issues. Use it carefully and certainly not in for-loops
– RPDeshaies
Jun 16 '15 at 14:55
add a comment |
1
Please be aware that if you're using this solution, you might run into issues when classes have the same name for properties, but with different types. For example:public class A { public int Age{get;set;}}
andpublic class B { public string Age{get;set;}}
Will throw an exception, if you're trying to convert fromA
toB
– Noctis
Apr 14 '14 at 0:32
This type of conversion could also lead to some huge performance issues. Use it carefully and certainly not in for-loops
– RPDeshaies
Jun 16 '15 at 14:55
1
1
Please be aware that if you're using this solution, you might run into issues when classes have the same name for properties, but with different types. For example:
public class A { public int Age{get;set;}}
and public class B { public string Age{get;set;}}
Will throw an exception, if you're trying to convert from A
to B
– Noctis
Apr 14 '14 at 0:32
Please be aware that if you're using this solution, you might run into issues when classes have the same name for properties, but with different types. For example:
public class A { public int Age{get;set;}}
and public class B { public string Age{get;set;}}
Will throw an exception, if you're trying to convert from A
to B
– Noctis
Apr 14 '14 at 0:32
This type of conversion could also lead to some huge performance issues. Use it carefully and certainly not in for-loops
– RPDeshaies
Jun 16 '15 at 14:55
This type of conversion could also lead to some huge performance issues. Use it carefully and certainly not in for-loops
– RPDeshaies
Jun 16 '15 at 14:55
add a comment |
There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.
In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.
public static T Transform<T>(this object myobj, string excludeFields = null)
{
// Compose a list of unwanted members
if (string.IsNullOrWhiteSpace(excludeFields))
excludeFields = string.Empty;
excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";
var objectType = myobj.GetType();
var targetType = typeof(T);
var targetInstance = Activator.CreateInstance(targetType, false);
// Find common members by name
var sourceMembers = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var targetMembers = from source in targetType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
// Remove unwanted members
commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));
foreach (var memberInfo in commonMembers)
{
if (!((PropertyInfo)memberInfo).CanWrite) continue;
var targetProperty = typeof(T).GetProperty(memberInfo.Name);
if (targetProperty == null) continue;
var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
if (sourceProperty == null) continue;
// Check source and target types are the same
if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;
var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
if (value == null) continue;
// Set the value
targetProperty.SetValue(targetInstance, value, null);
}
return (T)targetInstance;
}
that will work as long as you dont have ENUMS in your object as properties
– Natalia Z
Jun 29 '18 at 15:28
add a comment |
There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.
In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.
public static T Transform<T>(this object myobj, string excludeFields = null)
{
// Compose a list of unwanted members
if (string.IsNullOrWhiteSpace(excludeFields))
excludeFields = string.Empty;
excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";
var objectType = myobj.GetType();
var targetType = typeof(T);
var targetInstance = Activator.CreateInstance(targetType, false);
// Find common members by name
var sourceMembers = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var targetMembers = from source in targetType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
// Remove unwanted members
commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));
foreach (var memberInfo in commonMembers)
{
if (!((PropertyInfo)memberInfo).CanWrite) continue;
var targetProperty = typeof(T).GetProperty(memberInfo.Name);
if (targetProperty == null) continue;
var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
if (sourceProperty == null) continue;
// Check source and target types are the same
if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;
var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
if (value == null) continue;
// Set the value
targetProperty.SetValue(targetInstance, value, null);
}
return (T)targetInstance;
}
that will work as long as you dont have ENUMS in your object as properties
– Natalia Z
Jun 29 '18 at 15:28
add a comment |
There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.
In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.
public static T Transform<T>(this object myobj, string excludeFields = null)
{
// Compose a list of unwanted members
if (string.IsNullOrWhiteSpace(excludeFields))
excludeFields = string.Empty;
excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";
var objectType = myobj.GetType();
var targetType = typeof(T);
var targetInstance = Activator.CreateInstance(targetType, false);
// Find common members by name
var sourceMembers = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var targetMembers = from source in targetType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
// Remove unwanted members
commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));
foreach (var memberInfo in commonMembers)
{
if (!((PropertyInfo)memberInfo).CanWrite) continue;
var targetProperty = typeof(T).GetProperty(memberInfo.Name);
if (targetProperty == null) continue;
var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
if (sourceProperty == null) continue;
// Check source and target types are the same
if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;
var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
if (value == null) continue;
// Set the value
targetProperty.SetValue(targetInstance, value, null);
}
return (T)targetInstance;
}
There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.
In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.
public static T Transform<T>(this object myobj, string excludeFields = null)
{
// Compose a list of unwanted members
if (string.IsNullOrWhiteSpace(excludeFields))
excludeFields = string.Empty;
excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";
var objectType = myobj.GetType();
var targetType = typeof(T);
var targetInstance = Activator.CreateInstance(targetType, false);
// Find common members by name
var sourceMembers = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var targetMembers = from source in targetType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
// Remove unwanted members
commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));
foreach (var memberInfo in commonMembers)
{
if (!((PropertyInfo)memberInfo).CanWrite) continue;
var targetProperty = typeof(T).GetProperty(memberInfo.Name);
if (targetProperty == null) continue;
var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
if (sourceProperty == null) continue;
// Check source and target types are the same
if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;
var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
if (value == null) continue;
// Set the value
targetProperty.SetValue(targetInstance, value, null);
}
return (T)targetInstance;
}
answered Mar 4 '18 at 22:42
SpaceKatSpaceKat
5316
5316
that will work as long as you dont have ENUMS in your object as properties
– Natalia Z
Jun 29 '18 at 15:28
add a comment |
that will work as long as you dont have ENUMS in your object as properties
– Natalia Z
Jun 29 '18 at 15:28
that will work as long as you dont have ENUMS in your object as properties
– Natalia Z
Jun 29 '18 at 15:28
that will work as long as you dont have ENUMS in your object as properties
– Natalia Z
Jun 29 '18 at 15:28
add a comment |
Using this code you can copy any class object to another class object for same name and same type of properties.
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);
add a comment |
Using this code you can copy any class object to another class object for same name and same type of properties.
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);
add a comment |
Using this code you can copy any class object to another class object for same name and same type of properties.
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);
Using this code you can copy any class object to another class object for same name and same type of properties.
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);
answered Jun 20 '18 at 10:59
Yats_BhavsarYats_Bhavsar
463
463
add a comment |
add a comment |
var obj = _account.Retrieve(Email, hash);
AccountInfoResponse accountInfoResponse = new AccountInfoResponse();
if (obj != null)
{
accountInfoResponse =
JsonConvert.
DeserializeObject<AccountInfoResponse>
(JsonConvert.SerializeObject(obj));
}
image description
add a comment |
var obj = _account.Retrieve(Email, hash);
AccountInfoResponse accountInfoResponse = new AccountInfoResponse();
if (obj != null)
{
accountInfoResponse =
JsonConvert.
DeserializeObject<AccountInfoResponse>
(JsonConvert.SerializeObject(obj));
}
image description
add a comment |
var obj = _account.Retrieve(Email, hash);
AccountInfoResponse accountInfoResponse = new AccountInfoResponse();
if (obj != null)
{
accountInfoResponse =
JsonConvert.
DeserializeObject<AccountInfoResponse>
(JsonConvert.SerializeObject(obj));
}
image description
var obj = _account.Retrieve(Email, hash);
AccountInfoResponse accountInfoResponse = new AccountInfoResponse();
if (obj != null)
{
accountInfoResponse =
JsonConvert.
DeserializeObject<AccountInfoResponse>
(JsonConvert.SerializeObject(obj));
}
image description
edited Nov 23 '18 at 6:51
Keyur PATEL
2,0941936
2,0941936
answered Nov 23 '18 at 6:21
Varun Tej Reddy PutchakayalaVarun Tej Reddy Putchakayala
1
1
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3672742%2fcast-class-into-another-class-or-convert-class-to-another%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
This code doesn't make sense. Post code that compiles (it's not the cast that's the problem).
– µBio
Sep 8 '10 at 23:46
9
Quite harsh.. Missing a
class
keyword doesnt take the sense away.– nawfal
Jan 16 '14 at 4:56
There are existing lightweight mapper libraries written already for exactly this purpose. They handle a lot more edge cases. You can google it.
– nawfal
Jan 16 '14 at 5:15
First and easy solution: automapper.org
– Soren
May 14 '14 at 9:08