C# - CS0572 Error When Trying to Populate a Class - c#

C# Newbie Here.
I have a class below:
namespace CompanyDevice.DeviceResponseClasses
{
public class DeviceStatusClass
{
public class Root
{
public static string RequestCommand { get; set; }
}
}
}
In another namespace I have:
namespace CompanyDevice
{
public class StatusController : ApiController
{
public DeviceStatusClass Get()
{
var returnStatus = new DeviceStatusClass();
returnStatus.Root.RequestCommand = "Hello"; //'Root' is causing a CS0572 error
return returnStatus;
}
}
}
I'm sure I'm making some rudimentary error here. Could you please help me find it? Thanks.

You access static properties from the type, not from the instance.
DeviceStatusClass.Root.RequestCommand = "Command";
Because the property RequestCommand is static, there will only ever be one. Perhaps this is what you want, but likely is not based on your usage.
You can remove the static keyword from RequestCommand, then you can access it through the instance, however you will need to add a field or property for the instance of Root inside of DeviceStatusClass.
public class DeviceStatusClass
{
public Root root = new Root();
public class Root
{
public string RequestCommand { get; set; }
}
}
And use like you did originally.
public class StatusController : ApiController
{
public DeviceStatusClass Get()
{
var returnStatus = new DeviceStatusClass();
returnStatus.root.RequestCommand = "Hello";
return returnStatus;
}
}

You maybe have a java background. In c# nested classes only change the names, they do not make the parent class contain an instance of a child class
namespace CompanyDevice.DeviceResponseClasses
{
public class DeviceStatusClass
{
public class Root
{
public static string RequestCommand { get; set; }
}
public Root DeviceRoot {get;set;} <<<=== add this
}
}
and then
returnStatus.DeviceRoot.RequestCommand = "Hello";

Related

Get attribute information from inheriting class, inside static function

I have a situation where I need to get the value on a property on an attribute (decorator) applied to a class. That class that is decorated, is inheriting from an abstract class. It is this abstract class that needs to get the attribute information, but it needs to do so inside a static function.
I cannot post the exact scenario, but here is a terrible example that could do without attributes, but please work with it as it is:
public class VehicleShapeAttribute : Attribute
{
public string Shape { get; }
public VehicleShapeAttribute(string shape)
{
Shape = shape;
}
}
public abstract class Vehicle
{
public string Brand { get; set; }
public string Model { get; set; }
public string Colour { get; set; }
public static string GetVehicleShape()
{
//return value from the attribute, from this static function. CANT DO THIS HERE
return AnyInheritingClass.VehicleShapeAttribute.Shape;
}
}
[VehicleShape("sedan")]
public class VauxhaulAstraSedan : Vehicle
{
//calling GetVehicleShape() on this class should automatically return "sedan"
}
Is this possible?
This is a bad example but I cannot post the actual code
Make the method non-static and resolve the runtime type with this.GetType():
public abstract class Vehicle
{
public string Brand { get; set; }
public string Model { get; set; }
public string Colour { get; set; }
public string GetVehicleShape()
{
var attribute = Attribute.GetCustomAttribute(this.GetType(), typeof(VehicleShapeAttribute)) as VehicleShapeAttribute;
if(attribute is VehicleShapeAttribute){
return attribute.Shape;
}
return null;
}
}
For a static version, you'll need to accept a Vehicle parameter whose type you can then inspect:
public static string GetVehicleShape(Vehicle vehicle)
{
var attribute = Attribute.GetCustomAttribute(vehicle.GetType());
// ...
Alternatively (and I'm just copy/pasting Mathias' code into another form syntactically here) if you really need to have the method static because you don't want to create an instance, you can add the following method to your attribute code (or any other static class, but I like to put it there with the attribute):
public static string GetFrom<T>()
{
return GetFrom(typeof(T));
}
public static string GetFrom(Type t)
{
var attribute = Attribute.GetCustomAttribute(t, typeof(VehicleShapeAttribute)) as VehicleShapeAttribute;
if(attribute is VehicleShapeAttribute){
return attribute.Shape;
}
return null;
}
Then you could write code like:
var shape = VehicleShapeAttribute.GetFrom<VauxhaulAstraSedan>();
or
var shape = VehicleShapeAttribute.GetFrom(typeof(VauxhaulAstraSedan));
or even
var vehicle = new VauxhaulAstraSedan();
var shape = VehicleShapeAttribute.GetFrom(vehicle.GetType());

WCF CollectionDataContract Dictionary constructor

I'm using a WCF CollectionDataContract to pass data using a Dictionary and it is working very well.
[CollectionDataContract]
public class MyDataDictionary : Dictionary<string, MyItemValue> { }
[DataContract]
public class MyItemValue
{
[DataMember] public int ID { get; set; }
[DataMember] public string Name { get; set; }
// ...
public IP21ItemValue() {
ID = -1;
Name = string.Empty;
// ...
}
}
I want to enhance my dictionary so it is case insensitive and I've tried a variety of things similar to these:
// Attempt to put the argument on the declaration.
[CollectionDataContract]
public class MyDataDictionary : Dictionary<string, MyItemValue>(StringComparer.InvariantCultureIgnoreCase) { }
// Attempt to instantiate it within the constructor...
[CollectionDataContract]
public class MyDataDictionary : Dictionary<string, MyItemValue> {
public MyDataDictionary() {
this = new Dictionary<string, MyItemValue>(StringComparer.InvariantCultureIgnoreCase);
}
}
But I can't seem to make anything work. I'd really like to avoid wrapping the whole thing in a class where the dictionary is a data member. Is there a syntax that will do this?
Call the base class constructor, like this:
public class MyDataDictionary : Dictionary<string, MyItemValue> {
public MyDataDictionary()
:base(StringComparer.InvariantCultureIgnoreCase)
{
}
}

Assign static value to class from another class

My question is pretty much basic but I am not getting idea to do it. Please check the code bellow. My basic goal is to make a public class which will return some static data under a list. The example class model is provided bellow. See in class PaymentMethodDetials has two properties and I want to set value of this two property from class PaymentMethodList as a list then I will be using those list values outside this whole c# class model publically. Now my problem is paymentList.Add() visual studio not allowing me to do Add method. How can I fix that? Thanks in advance
namespace Test.Helpers
{
public class PaymentMethodList
{
List<PaymentMethodDetials> paymentList = new List<PaymentMethodDetials>();
paymentList.Add()//i want to insert data to "PaymentMethodDetials" this class like using "Add" which allowing now
}
public class PaymentMethodDetials
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Try this , hope this helps
namespace Test.Helpers
{
public class PaymentMethodList
{
List<PaymentMethodDetials> paymentList = new List<PaymentMethodDetial();
public PaymentMethodList()
{
paymentList.Add(new PaymentMethodDetials
{
Id=1,
Name="xyz"
});
}
}
public class PaymentMethodDetials
{
public int Id { get; set; }
public string Name { get; set; }
}
}

C# Resolving Base Class to Correct Repository Method Call Based on Implemented Type

In our current project, we have an abstract base user class that is implemented by multiple other user types. We have a comparison class that can compare any of these types and then needs to call a correct update api based on the implemented type. I am trying to avoid bringing an if(typeof(User)) logic tree into the code and was hoping to figure out some way to solve the issue with method overloading. Are there any design patterns that can help solve this issue with some type of interface that can be dependency injected? Here is a basic code example
using System;
using System.Collections.Generic;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
List<BaseUser> TestUsers = new List<BaseUser>();
TestUsers.Add(new UserA() { Email = "test1#test.com", Location = "New York, NY" });
TestUsers.Add(new UserB() { Email = "test2#test.com", State = "TN" });
foreach (var user in TestUsers)
{
//need to invoke the correct Print repo method based on the actual user type, possible interface?
}
Console.Read();
}
}
public abstract class BaseUser
{
public string Email { get; set; }
}
public class UserA : BaseUser
{
public string Location { get; set; }
}
public class UserB : BaseUser
{
public string State { get; set; }
}
public class UserARepo
{
void Print(UserA user)
{
Console.Write($"User A Saved {user.Email}, {user.Location}");
}
}
public class UserBRepo
{
void Print(UserB user)
{
Console.Write($"User B Saved {user.Email}, {user.State}");
}
}
}
If the Print methods only need the Email and Location/State properties of the objects, then change their signature to accept only these two strings.
I would add a common property to the abstract class, which returns the needed property in the User* classes:
namespace ConsoleApplication5
{
public abstract class BaseUser
{
public string Email { get; set; }
public string OtherLocation { get; set;}
}
public class UserA : BaseUser
{
public string Location { get; set; }
public string OtherLocation {
get
{
return this.Location;
}
set
{
this.Location = value;
}
}
}
public class UserB : BaseUser
{
public string State { get; set; }
public string OtherLocation {
get
{
return this.State;
}
set
{
this.State = value;
}
}
}
public class UserARepo
{
void Print(BaseUser user)
{
Console.Write($"User A Saved {user.Email}, {user.OtherLocation}");
}
}
public class UserBRepo
{
void Print(BaseUser user)
{
Console.Write($"User B Saved {user.Email}, {user.OtherLocation}");
}
}
}
Hopefully I'm understanding the problem correctly - but if each of those UserTypes needs an update API or Print Repo method, put them as abstract methods in the class:
public abstract class BaseUser
{
public string Email { get; set; }
public abstract void PrintRepo();
}
Basically, it's just a question of: what functionality is required of the subclasses if they want to implement your base class? They have to handle Update requests? Then put an abstract declaration in the abstract class that says, "Hey, if you inherit from me, you have to include an Update function."
Then your main function becomes something like:
foreach (var user in TestUsers)
{
user.PrintRepo();
}

Static method return base class instance

I have the following classes:
//some base class
public abstract class MyObject<T>{
public static T FromObject(object anotherObject){
var t = Activator.CreateInstance<T>();
// some reflection logic here
return t;
}
}
public class Product: MyObject<Product>{
}
public class ProductCart: MyObject<ProductCart>{
public ICollection<Product> Products{get;set;}
}
public class Basket: ProductCart{
public int BasketId{get;set;}
}
public class Order: ProductCart{
public int OrderId{get;set;}
}
So now I could build my model like this:
var products = serviceContext.Products.Select(Product.FromObject).ToList(); // no problem here
var basket = Basket.FromObject(serviceContext.Basket); // problem is here - instance of ProductCart is returned
var order = Order.FromObject(serviceContext.Order); // same problem, instance of ProductCart
Is there a way somehow to solve it and get converted Basket and Order instead of base ProductCart?
The goal is:
var basket = Basket.FromObject(serviceContext.Basket); // return instance of Basket inherited from ProductCart
Thanks for helping.
If you can change the class definitions, you can pass along the type to ProductCart, like so:
public class ProductCart<T> : MyObject<T> { }
public class Basket : ProductCart<Basket> { }
public class Order : ProductCart<Order> {}
In your definition you tell Basket.FromObject to explicitly return ProductCarts (by inheriting from MyObject<ProductCart>).
And if you're unable to change the inherit tree, you can choose to hide the original method (or place it in a factory):
public class Basket : ProductCart
{
public int BasketId { get; set; }
public Basket FromObject(object anotherObject)
{
return MyObject<Basket>.FromObject(anotherObject);
}
}
That's because Basket is a MyObject<ProductCart>, and not a MyObject<Basket>.
If you don't want to redefine your hierarchy, you should define the return type of the static method according to the object you pass, like in this example:
using System;
public abstract class MyObject<T> {
public static TOtherObject FromObject<TOtherObject>(TOtherObject anotherObject) where TOtherObject : MyObject<T> {
var newOtherTypeInstance = Activator.CreateInstance<TOtherObject>();
// some reflection logic here
return newOtherTypeInstance;
}
}
public class ProductCart : MyObject<ProductCart> {
}
public class Basket : ProductCart {
public int BasketId { get; set; }
}
public class Order : ProductCart {
public int OrderId { get; set; }
}
class Program {
static void Main(string[] args) {
Order o = new Order();
var basket = Basket.FromObject(o);
}
}
Of course, at this point the actual implementation of the comment "some reflection logic here" could get much more complicated :)

Categories

Resources