I'm using class from some assembly(source code is not available), so it is not possible to change their's code I need to add extension method for explicit cast operator, is there any way to achieve that? (I have tried to add as regular extension method, but without success)
public static explicit operator MembershipUser(this MembershipUser membership, User user)
{
return new MembershipUser("SimplyMembershipProvider", user.UserName, user.UserId, user.Email, null, null, user.IsApproved, user.IsLocked,
user.CreateDate, user.LastLoginDate, user.LastActivityDate, user.CreateDate, DateTime.MinValue);
}
how can i solve this?
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.
LinqExtensionMethod.zip. Linq provides standard query operators like filtering, sorting, grouping, aggregation, and concatenations, and it has many operators to achive many types of functionalities, which are called extension methods, in LINQ.
You cannot overload operators via Extension methods.
Best you can do with an extension method:
public static MembershipUser ConvertToMembershipUser(this User user)
{
return new MembershipUser("SimplyMembershipProvider",
user.UserName,
user.UserId,
user.Email,
null,
null,
user.IsApproved,
user.IsLocked,
user.CreateDate,
user.LastLoginDate,
user.LastActivityDate,
user.CreateDate,
DateTime.MinValue);
}
MembershipUser membershipUser = aUser.ConvertToMembershipUser();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With