How to capture value OOPS & Generic [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
here is my code given.
class Program
{
static void Main(string[] args)
{
var _User = new User { Name="Test", Age=12 };
_User.Save();
}
}
public class DBObject<T>
{
public void Save()
{
}
}
public class User : DBObject<User>
{
public string Name { get; set; }
public int Age { get; set; }
}
i want to capture user name & age from save method ? how could i do so......plzz guide. thanks

While looking at your code, why would one want to read class specific properties in a generic method?
The only solutions i see is to use Reflection, or create an abstract base class with a before save method and call that method in de Save() method. Add a generic type constraint to the DBObject class defining that T is of the basetype. This way you can add class specific functionality to a generic method. Something like this:
public abstract class Base
{
public virtual void BeforeSave()
{
}
}
public class User : Base
{
public string Name { get; set; }
public int Age { get; set; }
public override void BeforeSave()
{
// You can access your properties here
if (this.Name.Trim() == "")
throw new Exception("Name is mandatory!")
}
}
public class DBObject<T>
where T: Base
{
public void Save()
{
T.BeforeSave();
}
}

Related

Is it possible to remove property from Custom Class in c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
public class abc
{
public int id{get;set;}
public string name{get;set;}
}
I want to remove property name from class abc dynamically. is it possible in c#?
No, after compilation the class definition can't be changed. What you can do is. Make a list of properties you want to Ignore.
or you can Create a custom attribute. Add it on the property then get the List of Properties excluding the ones with that Attribute
For example
public class abc
{
public int id{get;set;}
[IgnoredProperty]
public string name{get;set;}
}
Now In Loop For example you can do this.
foreach (var prop in typeof(abc).GetProperties().Where(x => !Attribute.IsDefined(x,typeof(IgnoredProperty))).ToList())
{
}
This can be the attribute Class
public class IgnoredPropertyAttribute : Attribute
{
}
Ignoring "dynamic" for the moment, here's what you could do with interfaces:
public interface IAbcId {
Id {get; set;}
}
public class Abc : IAbcId {
public Id {get; set;}
public Name {get; set;}
}
....
public class Consumer {
void CallingFunction()
{
var obj = new Abc();
// obj will have Name and Id properties visible here
ConsumingFunction(obj)
// or
IAbcId iAbc = new Abc();
//iAbc.Name will not be visible here
}
void ConsumingFunction ( IAbcId item )
{
// item will only have Id property visible.
}
}

how to do grouping of the data.I want to show a list which on click contains data of foo and on click of it data of boo [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a resobject with structure like this.
public class resobject
{
public IList<foo> Foo{get;set}
public string message{get;set;}
}
public class foo
{
public IList<boo> Boo{get;set}
}
public class boo
{
public string category{get;set;}
}
currently i am having resobject data.How to reach to boo class and access the data.
public class Program
{
public class resobject
{
public IList<foo> Foo{get;set;}
public string message{get;set;}
}
public class foo
{
public IList<boo> Boo{get;set;}
}
public class boo
{
public string category{get;set;}
}
public static void Main()
{
var root = new resobject();
foreach(var f in root.Foo)
{
foreach(var b in f.Boo)
{
b.category = "value";
}
}
}
}

Convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.IList<>' [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
In my model Account I have a property like this
public List<String> Roles { get; set; }
Later on I want to get that property but convert it IList<IApplicationUserRole<Role>>, so I have this function
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles; // how do I convert this in the specific type intended.
}
}
Here is my IApplicationUserRole
public interface IApplicationUserRole<TRoleModel> : IRole<string>
where TRoleModel : EntityModel
{
TRoleModel Role { get; set; }
String Name { get; set; }
}
I am a newbie to this thing. Looking forward for any help.
Say you have your implementing class be something like:
public class ApplicationUserRole : IApplicationUserRole<T> where T : Role
{
public ApplicationUserRole()
{
}
public User User { get; set; }
public T Role { get; set; }
}
Then, you'd do something like this:
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles
.Select(r => new ApplicationUserRole { Role = roleService.FindRoleByName(r) })
.Cast<IApplicationUserRole<Role>>()
.ToList();
}
}
Where roleService is some way of building a Role instance from the role name (which above is r)
NOTE: This being said, there is a catch in the above implementation. Since Roles is a property it should not do data access operations. So, in this case, you should create a method instead of a property.
I would start with something like this:
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles.Select(r=>
new ApplicationUserRole<Role>() {Name = r})
.Cast<IApplicationUserRole<Role>>()
.ToList();
}
}
This assuming that you have a class that implements the IApplicationUserRole<Role> interface.
As #MartinLiversage says you can't directly convert List<T> to List<U>, you have to manually do the conversion.

Declaring class as properties inside another class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I copied this code from this article and I don't get any idea why define class inside classes as properties. Also, what happens when the class PersonalLoan is instantiated ?
public class PersonalLoan
{
public string AccountNumber { get; set; }
public string AccounHolderName { get; set; }
public Loan LoanDetail { get; set; }
public PersonalLoan(string accountNumber)
{
this.AccountNumber = accountNumber;
this.AccounHolderName = "Sourav";
this.LoanDetail = new Loan(this.AccountNumber);
}
}
public class Loan
{
public string AccountNumber { get; set; }
public float LoanAmount { get; set; }
public bool IsLoanApproved { get; set; }
public Loan(string accountNumber)
{
Console.WriteLine("Loan loading started");
this.AccountNumber = accountNumber;
this.LoanAmount = 1000;
this.IsLoanApproved = true;
Console.WriteLine("Loan loading started");
}
}
I suspect that this code snippet is an example of what you should avoid: LoanDetail property of type Loan inside a class PersonalLoan suggests a has-a relationship between the classes. In other words, the authors of this code snippet are trying to say that
Personal loan has a Loan
This, however, is unlikely the relationship that they are trying to model: in reality,
Personal loan is a Loan
The relationship is-a is modeled using inheritance, not composition. In other words, they should have written this:
public class PersonalLoan : Loan {
public PersonalLoan(string accountNumber) : base(accountNumber) {
...
}
...
}
Another issue that points to the model being incorrect is that both PersonalLoan and the Loan inside it have the same accountNumber, which is stored in two places within the same object. When you see this, you know something is not right. The reason you get two account numbers is that when PersonalLoan gets instantiated, its constructor also instantiates Loan, passing it the same accountNumber.
This is not to say that embedding objects inside other objects is wrong. For example, if you were to model a borrower address as a class, you would end up with something like this:
class Address {
public string Country {get;set;}
public string City {get;set;}
... // And so on
}
class Borrower {
public Address MailingAddress {get;set;}
... //
}
This model is perfectly valid, because Borrower has an Address.

C# Generic Constraints not working correctly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following code:
public interface IEnrollment
{
bool IsGood { get; set; }
}
public interface IEnrollmentToRegion
{
int RegionId { get; set; }
}
public class ByRegion : IEnrollmentToRegion
{
public int RegionId { get; set; }
}
public class Enrollment : IEnrollment
{
public bool IsGood { get; set; }
public ICollection<ByRegion> Regions { get; set; }
}
public class Main
{
public void DoSomething()
{
var e = new Enrollment();
if (isEnrolled(e, c => c.Any(l => l.RegionId == 10)))
{
}
}
private bool isEnrolled<T>(Enrollment enrollment, Func<ICollection<T>, bool> test) where T : IEnrollmentToRegion
{
return true;
}
}
What I'm trying to do is create the method isEnrolled that takes and object of the type IEnrollment and in this method I will do a bunch of checks to see if it return true or not. One of the things that I want to check is a collection of objects (in the above example it is simplified to only have 1 single class the ByRegion class, but in my real there are multiple Enrollment classes each with it's own separate collections under them that are of different types, but all of the types have a property called RegionId.
So I want to pass in a function that will check these various collections to see if the RegionId is in the collection. The problem that I'm having is that I get an error on the line
c.Any(l => l.RegionId == 10)) saying that it doesn't know what RegionId is. In fact when I hit the . after the l I do not get any intellisense drop down. I'm not sure why I don't get any dropdown because there is a restriction on T that T should be of the IEnrollmentToRegion type and that type has RegionId on it.
Your problem is that while a ByRegion is an IEnrollmentToRegion, an ICollection<ByRegion> is not a ICollection<IEnrollmentToRegion>. You can test this using reflection:
//Returns true
return typeof(IEnrollmentToRegion).IsAssignableFrom(typeof(ByRegion));
//Returns false
return typeof(ICollection<IEnrollmentToRegion>).IsAssignableFrom(typeof(ICollection<ByRegion>));
So you can't just specify T and let type inference take care of it for you. In fact, even if you specified the type explicitly, like:
isEnrolled<IEnrollmentToRegion>(e, c => c.Any(l => l.RegionId == 10))
You'd find that once you try to write the actual contents of isEnrolled<T>, you'd run into problems.
Here's an updated version of your code that works:
public interface IEnrollment<T> where T:IEnrollmentToRegion
{
bool IsGood { get; set; }
ICollection<T> Regions { get; set; }
}
public interface IEnrollmentToRegion
{
int RegionId { get; set; }
}
public class ByRegion : IEnrollmentToRegion
{
public int RegionId { get; set; }
}
public class Enrollment : IEnrollment<ByRegion>
{
public bool IsGood { get; set; }
public ICollection<ByRegion> Regions { get; set; }
}
public class Main
{
public void DoSomething()
{
var e = new Enrollment();
e.Regions = new List<ByRegion>() { new ByRegion { RegionId = 10 } };
if (isEnrolled(e, c => c.Any(l => l.RegionId == 10)))
{
//This line gets hit
}
}
private bool isEnrolled<T>(IEnrollment<T> enrollment, Func<ICollection<T>, bool> test) where T : IEnrollmentToRegion
{
return test(enrollment.Regions);
}

Categories