I have the following classes:
class Given
{
public string text = "";
public List<StartCondition> start_conditions = new List<StartCondition>();
};
class StartCondition
{
public int index = 0;
public string device = "unknown";
public string state = "disconnected";
public bool isPass = false;
};
I want to convert them into c# properties (using get; and set;)
Looking at this question: what-is-the-get-set-syntax-in-c, it seems I can make a property nice and easy like this:
class Given
{
public string text { get; set; }
public List<StartCondition> start_conditions { get; set; }
};
class StartCondition
{
public int index { get; set; }
public string device { get; set; }
public string state { get; set; }
public bool isPass { get; set; }
};
But now I don't know how I should add my initialisations, because I want the same start values as I had before, or for the List container I want it to be new'ed.
What is the best way to achieve this?
The ability to have auto property initializers is included since C# 6.0. The syntax is:
public int X { get; set; } = x; // C# 6 or higher
Use a constructor. So your class would look like this:
public class StartCondition
{
public int index { get; set; }
public string device { get; set; }
public string state { get; set; }
public bool isPass { get; set; }
// This is the constructor - notice the method name is the same as your class name
public StartCondition(){
// initialize everything here
index = 0;
device = "unknown";
state = "disconnected";
isPass = false;
}
}
Create a Constructor to start your class instance with the default values
class Given
{
public Given(){
this.text = "";
start_conditions = new List<StartCondition>();
}
public string text { get; set; }
public List<StartCondition> start_conditions { get; set; }
};
class StartCondition
{
public StartCondition(){
this.index = 0;
this.device = "unknown";
this.state = "disconnected";
this.isPass = false;
}
public int index { get; set; }
public string device { get; set; }
public string state { get; set; }
public bool isPass { get; set; }
};
Now you can create your instances with the default values by using StartCondition A = new StartCondition();
If you are not using C# 6+ (or even if you are), you can explicitly declare your backing variables for properties:
public class Given
{
private string _text = string.Empty;
private List<StartCondition> _start_conditions = new List<StartCondition>();
public string text { get{ return _text; } set{ _text = value; } }
public List<StartCondition> start_conditions { get{ return _start_conditions; } set{ _start_conditions = value; } }
}
This allows you to set your initializations as before.
Related
I'm sure someone has tried to do something like this before, but I'm unsure if what I'm finding in my searches fits what I'm trying to do.
In my .Net 6 Web API I have a class to get data passed by the request:
public abstract class QueryStringParameters {
private readonly int _maxPageSize = Constants.DefaultPageSizeMax;
private int _pageSize = Constants.DefaultPageSize;
public int? PageNumber { get; set; } = 1;
public int? PageSize {
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value ?? Constants.DefaultPageSize;
}
public string OrderBy { get; set; }
public string Fields { get; set; }
}
For each controller I create a view model which inherits from this:
public class ProgramParameters : QueryStringParameters {
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
...
public ProgramParameters() {
// Default OrderBy
OrderBy = "Id";
}
}
This works fine when calling an endpoint expecting multiple results and single results. However, I want to split the QueryStringParameters properties that are for pagination, something like this:
public abstract class QueryStringParameters {
public string Fields { get; set; }
}
public abstract class QueryStringParametersPaginated : QueryStringParameters {
private readonly int _maxPageSize = Constants.DefaultPageSizeMax;
private int _pageSize = Constants.DefaultPageSize;
public int? PageNumber { get; set; } = 1;
public int? PageSize {
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value ?? Constants.DefaultPageSize;
}
public string OrderBy { get; set; }
}
The problem is that then my view modal looks like this:
public class ProgramParameters : QueryStringParameters {
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
...
public ProgramParameters() {
}
}
public class ProgramParametersPaginated : QueryStringParametersPaginated {
public bool MapDepartment { get; set; } = true; // repeated
public bool MapAnother1 { get; set; } = true; // repeated
public bool MapAnother2 { get; set; } = true; // repeated
...
public ProgramParameters() {
// Default OrderBy
OrderBy = "Id";
}
}
How can I rewrite this so that ProgramParameters and ProgramParametersPaginated don't have to have the same properties (MapDepartment, MapAnother1, MapAnother2) defined in both?
I tried something like this but that's not allowed and I am unsure how to proceed.
public class ProgramParametersPaginated : ProgramParameters, QueryStringParametersPaginated {
public ProgramParametersPaginated() {
// Default OrderBy
OrderBy = "Id";
}
}
If I understood correctly, you need to extract interfaces instead of using classes as you did, so you can apply multiple implementation.
First define the interfaces and constants for you filter properties:
public enum Constants
{
DefaultPageSizeMax = 500,
DefaultPageSize = 100
}
public interface IQueryStringParameters
{
string Fields { get; set; }
}
public interface IQueryStringParametersPaginated : IQueryStringParameters
{
string OrderBy { get; set; }
int PageSize { get; set; }
int MaxPageSize { get; set; }
int? PageNumber { get; set; }
}
Then you create an abstract class that inherit from both interfaces defined so you can write some behaviour like you did with the setters and getters:
public abstract class BaseProgramParameters : IQueryStringParameters, IQueryStringParametersPaginated
{
public string Fields { get; set; }
public string OrderBy { get; set; }
private int _pageSize = (int)Constants.DefaultPageSize;
private int _maxPageSize = (int)Constants.DefaultPageSizeMax;
public int PageSize
{
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value;
}
public int MaxPageSize { get; set; }
public int? PageNumber { get; set; }
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
public BaseProgramParameters()
{
}
public BaseProgramParameters(string orderBy)
{
this.OrderBy = orderBy;
}
}
Since you may want to define a different value on MapDeparment, MapAnother, etc, you can use the constructor on the child classes:
public class ProgramParametersPaginated : BaseProgramParameters
{
public ProgramParametersPaginated() : base("Id")
{
}
}
public class ProgramParameters : BaseProgramParameters
{
public ProgramParameters()
{
this.MapAnother1 = false;
}
}
Let me know if you have any further doubts.
I have 2 lists
public class EmailDetails
{
public int EmailMasterID { get; set; }
public string Name { get; set; }
public string Body { get; set; }
public string Number { get; set; }
public string IsModified { get; set; }
}
public class EmailDetailsActual
{
public string ProgramNumber { get; set; }
public string IsModified { get; set; }
public int EmailMasterID_FK { get; set; }
}
I need to set value of IsModified column to YES in EmailDetails list if EmailMasterID = EmailMasterID_FK (from EmailDetailsActual list) . If not, then set value to NO. The final result should be EmailDetails list.
im not sure but i put new EmailDetailsActual in EmailDetails and I put the details for that (ProgramNumber , IsModified , EmailMasterID_FK)
and then I put input to when Call EmailDetails , should fill inputs like
EmailDetails p1 = new EmailDetails("ProgramNumber", "IsModified", 0000);
after i put IsModified Get properties in EmailDetails >>
if (EmailMasterID == EDA.EmailMasterID_FK)
{
return "yes";
}
else
{
return "no";
}
// EDA is new EmailDetailsActual
And I accessed it values in a this way (accessed EmailMasterID_FK (we create new EmailDetailsActual ) )
and its my finally >>>
public class EmailDetails
{
EmailDetailsActual EDA = new EmailDetailsActual();
public EmailDetails(string ProgramNumber , string IsModified , int EmailMasterID_FK)
{
EDA.ProgramNumber = ProgramNumber;
EDA.IsModified = IsModified;
EDA.EmailMasterID_FK = EmailMasterID_FK;
}
public int EmailMasterID { get; set; }
public string Name { get; set; }
public string Body { get; set; }
public string Number { get; set; }
public string IsModified { get
{
if (EmailMasterID == EDA.EmailMasterID_FK)
{
return "yes";
}
else
{
return "no";
}
}
}
}
public class EmailDetailsActual
{
public string ProgramNumber { get; set; }
public string IsModified { get; set; }
public int EmailMasterID_FK { get; set; }
}
this is example to work >>
EmailDetails p1 = new EmailDetails("ProgramNumber", "IsModified",9991);
p1.EmailMasterID = 9992;
Console.WriteLine(p1.IsModified);
its output no bc EmailMasterID (9991) its not same with EmailMasterID_FK(9992)
I hope I able to help you :)
Assigning values to instance variables of a class.
I have the following class with the following properties. It contains two static properties also.
public class Levels
{
public static string LevelWeek { get; private set; }
public static string LevelHours {get; private set; }
public int Start { get; set; }
public int Length { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string LevelType { get; set; }
}
I am assigning values to the properties in a method as follows :
Levels level = new Levels
{
Start = Convert.ToInt32(Request["start"]),
Length = Convert.ToInt32(Request["length"]),
Name = Request[("columns[3][search][value]")],
Address = Request[("columns[4][search][value]")],
LevelType = Request[("columns[6][search][value]")]
// I want to achieve this inside the object initialisation
if (string.IsNullOrEmpty(LevelType) {
LevelWeek = "Not set";
LevelHours = "Not set";
}
else {
if (LevelType.Equals("Junior") {
LevelWeek = LevelType;
} else
{
LevelHours = "Senior";
}
}
};
Then, I am passing the object level to a method like this.
AssignDetails(level);
The reason that I am using LevelWeek and LevelHours as static is that I want to preserve the variable of each even if the condition is not met on second hit of the method.
Note that I will access the variable LevelWeek and LevelHours in the method AssignDetails. Could someone please help me with this ?
EDITED
Currently I am having this :
public static string levelTypeCountry { get; private set; }
public static string levelTypeWeek { get; private set; }
public static string RateCountry { get; private set; }
public static string RateWeek { get; private set; }
public ActionResult IndexPagination()
{
int start = Convert.ToInt32(Request["start"]);
int length = Convert.ToInt32(Request["length"]);
string name = Request["search[value]"];
string address = Request[("columns[3][search][value]")];
string levelType = Request[("columns[6][search][value]")];
string rateType = Request[("columns[7][search][value]")];
if (string.IsNullOrEmpty(levelType))
{
levelTypeCountry = "";
levelTypeWeek = "";
}
else
{
if (CheckDate(levelType))
{
levelTypeWeek = levelType;
}
else
{
levelTypeCountry = levelType;
}
}
if (string.IsNullOrEmpty(rateType))
{
RateCountry = "";
RateWeek = "";
}
else
{
if (CheckDate(rateType))
{
RateWeek = rateType;
}
else
{
RateCountry = rateType;
}
}
var items = AssignDetails(start, length, name, address, levelTypeWeek, levelTypeCountry, RateWeek, RateCountry);
return items;
}
The function CheckDate just checks if the levelType is a date. If true, it returns true otherwise false.
The rateType and levelType returns different values. Sometimes, they return a date and sometimes a string word like "FRA".
I guess a setValue and 2 getValue methods are all that you need:
public class Levels {
private string LevelWeek {
get;
set;
}
private string LevelHours {
get;
set;
}
public int Start {
get;
set;
}
public int Length {
get;
set;
}
public string Name {
get;
set;
}
public string Address {
get;
set;
}
public string LevelType {
get;
set;
}
public void setValue() {
if (string.IsNullOrEmpty(LevelType) {
this.LevelWeek = "Not set";
this.LevelHours = "Not set";
} else {
if (LevelType.Equals("Junior") {
this.LevelWeek = LevelType;
} else {
this.LevelHours = "Senior";
}
}
}
public string getLevelWeek() {
return this.LevelWeek;
}
public string getLevelHours() {
return this.LevelHours;
}
}
}
}
When you declare your object :
var level = new Levels {
Start = Convert.ToInt32(Request["start"]),
Length = Convert.ToInt32(Request["length"]),
Name = Request[("columns[3][search][value]")],
Address = Request[("columns[4][search][value]")],
LevelType = Request[("columns[6][search][value]")]
}
// set value to LevelWeek / LevelHours
level.setValue();
// In AssignDetails function : get the value of LevelWeek and LevelHours:
var levelweek = level.getLevelWeek();
var levelhours = level.getLevelHours();
I am using enum for my group description in listview and I am trying to make it display some more user friendly text but I getting an error which says cannot implicitly convert type string to Mærke
Enum
public enum Mærke {
Alfa_Romeo,
Audi,
Aston_Martin__________________________________________________________5x114,
BMW,
Chervolet,
Chrysler,
Citroën,
Daewoo,
Daihatsu,
Dodge,
Ferrari };
public Mærke mærke { get; set; }
Class
public class biler
{
public string billed { get; set; }
public string Model { get; set; }
public string Type { get; set; }
public string Årgang { get; set; }
public string Krydsmål { get; set; }
public double ET { get; set; }
public double centerhul { get; set; }
public string bolter { get; set; }
public string hjul { get; set; }
public Mærke mærke { get; set; }
}
List
items.Add(new biler() { billed = "img/Biler/aston martin.png", Model = "DB9", Årgang = "03-", Krydsmål = "5x114.3", ET = 62.5, centerhul = 68.1, bolter = "M14x2", mærke = Mærke.Aston_Martin__________________________________________________________________________________________________5x114 });
CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView (hjuldata.ItemsSource);
PropertyGroupDescription groupDescription = new PropertyGroupDescription("mærke");
view.GroupDescriptions.Add(groupDescription);
var mærke = Merke.Alfa_Romeo; // example
var withSpaces = mærke.ToString().Replace("_", " ");
This should solve it for you. There's nothing built-in to do that so you COULD write an extension method like such:
public static string WithSpaces(this enum theEnum){
return theEnum.ToString().Replace("_", " ");
}
and then just use that in your code:
var mærke = Mærke.Alfa_Romeo.WithSpaces();
this should do it if that is what you are looking for and as for the picture i dont think headers supports that
using System.Reflection;
public static class EnumExtensions
{
public static string DisplayName(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
EnumDisplayNameAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))
as EnumDisplayNameAttribute;
return attribute == null ? value.ToString() : attribute.DisplayName;
}
}
public class EnumDisplayNameAttribute : Attribute
{
private string _displayName;
public string DisplayName
{
get { return _displayName; }
set { _displayName = value; }
}
}
public enum Mærke
{
[EnumDisplayName(DisplayName = "Alfa Romeo 5x114")]
Alfa_Romeo,
public string mærke { get; set; }
mærke = Mærke.Alfa_Romeo.DisplayName()
I have class which contains many properties:
public class Report
{
public int reportId { get; set; }
public string sentDate { get; set; }
public string photoName { get; set; }
public string state { get; set; }
public string patientName { get; set; }
public string doctorName { get; set; }
public string sex { get; set; }
public int isPregnant { get; set; }
public float weight { get; set; }
public float height { get; set; }
public int age { get; set; }
public string information { get; set; }
public string response { get; set; }
then I implement one constructor with argmuents :
public Report(int id, string photoName, string sentDate, string state,string response)
{
this.reportId = id;
this.photoName = photoName;
this.sentDate = sentDate;
this.state = state;
this.response = response;
}
finally I implement method which calls this constructor :
public static List<Report> GetListReportByEmail(string email)
{
DataTable dt = SqlHelper.ExecuteDataset(
new SqlConnection(Tls.ConnStr),
"spReportGetByEmail",
email).Tables[0];
List<Report> tempItems = new List<Report>();
if (dt.Rows.Count != 0)
{
foreach (DataRow rw in dt.Rows)
{
tempItems.Add(
new Report(
int.Parse(rw["ReportId"].ToString()),
Tls.GetBasicUrl() + "/Zdnn000kjUpload/__zd__MedicalConsultation/"
+ rw["PhotoName"].ToString(),
DateTime.Parse(rw["SentDate"].ToString()).ToString("dd/M/yyyy"),
rw["State"].ToString(),
rw["Response"].ToString()));
}
return tempItems;
}
else
{
return null;
}
}
but when I check the return, in addition of the properties mentionned in the constructor I found all properties which its type is int or float with the value 0.
I need this methods for a web services. when I test this web serives I found properties mentionned in the constructor ,but also int and float which are not populated:
<Report>
<reportId>4</reportId>
<sentDate>21/6/2014</sentDate>
<photoName>
http://localhost:2055/Zdnn000kjUpload/__zd__MedicalConsultation/
</photoName>
<state/>
<isPregnant>0</isPregnant>
<weight>0</weight>
<height>0</height>
<age>0</age>
<response/>
</Report>
Knowing that the stored procedure is ok.
So can any one help me to transmit only variables mentionned in the constructor : I don't need age,height,weight,isPregnant to be transmitted
Thanks.
Your constructor only assigns the following:
this.reportId = id;
this.photoName = photoName;
this.sentDate = sentDate;
this.state = state;
this.response = response;
Why would you expect the other properties (isPregnant, weight, height, age, etc.) to be populated as well? You are not assigning those properties value at any point.