Getting and setting defalut property value in c# - c#

class Log
{
public int LocationId { set { value = 1; } get; }
}
Will this set the default value for Log as 1 when i use like this: Log
l=new log(); Console.Writeline(l.LocationId);
?
I am aware of the normal way of using a property but will this also work?

The proper way to do it is in the constructor:
class Log {
public Log() {
LocationId = 1;
}
public int LocationId { set; get; }
}

No, you should do like this:
class Log
{
private int locationID = 1; //This is a default value
public int LocationId
{
set
{
locationID = value;
}
get
{
return locationID;
}
}
}

Related

Is the property of an object set or not?

I would like to know if there is a way to know if a parameter has been set. For example I have my object User.
public class User{
public int Oid{ get; set; }
public string Name{ get; set; }
public string Test{ get; set; }
}
I create an instance of my object and I set the property Oid and Name but not Test. I would like know this.
User u = new User();
u.Oid = 1;
u.Name = "Test";
It's possible?
TY
For reference types, a property (or field) which is not set will have the value null. Because string is a reference type, you can check this very easy:
if(u.Test == null)
{
Console.WriteLine("Property test of variable u is not set!");
}
For other types it is not so easy. bool variables will be false by default, and all numeric values like int uint, double etc will be 0. But of course, somebody might have set it fully aware to these values.
You can get the default value of any type via the following:
int x = default(int); // will be 0
string y = default(y); // will be null
bool z = default(bool); // will be false;
ADDENDUM: A completely different approach will be the following:
public class User{
public int Oid{ get; set; }
public string Name{ get; set; }
private string test;
public string Test
{
get { return test; }
set {test = value; IsTestSet = true; }
}
public bool IsTestSet {get; private set;}
}
With this code, you can check the property IsTestSet to determine whether the setter was called at least once.
This's my personal solution.
public short oid;
public short Oid
{
get { return oid; }
set
{
oid = value;
AddListaSet("Oid");
}
}
// for all parameter
List<string> ListSet { get; set; } = new List<string>();
private void AddListSet(string name)
{
if (ListSet.Contains(name) == false)
ListSet.Add(name);
}
public bool IsSet(string name)
{
return ListSet.Contains(name) ? true : false;
}

Caught "Specified cast is not valid." error on receiving data in C# ASP.net MVC?

I'm new to Entity Framework. I was trying to get my data from my local database through this basic line of code, I wanted to store all of the objects in the "Object" row into a list.
But it seems like it doesn't work, whatever I try. I'm running SQL server, ASP.NET MVC. My code is something like these:
[HttpGet]
public List<Object> Function1()
{
List<Object> result = new List<Object>();
using (DatabaseContext db = new DatabaseContext())
{
result = db.Object.ToList();
// ...
return result;
}
}
It always ended up with "Specified cast is not valid." error:
This is where the error was caught:
Line 137: result = db.Object.ToList();
This is my model class, I added some functions though, but I haven't changed any default properties that Entity set up for me :
public partial class Object
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public int Like { get; set; }
public int View { get; set; }
public byte Level
{
get { return Level; }
set
{
if (value < 1 || value > 3)
{
Level = 1;
throw new Exception("Level must be in 1 to 3. By default, it becomes 1");
}
else
{
Level = value;
}
}
}
public string Introduction { get; set; }
public string VideoUrl { get; set; }
public string Tag { get; set; }
public string Steps { get; set; }
public DateTime Date { get; set; }
public Object(string name, byte level, string introduction = null)
{
this.Name = name;
this.Level = level;
this.Introduction = introduction;
}
}
Is it oke to add functions and fix the properties like that ??
This is my table design in sql : pic
You have used public byte Level auto-property with a custom setter method.
This should be accompanied with a private backing variable. Something like
private byte _level
public byte Level
{
get { return _level; }
set
{
if (value < 1 || value > 3)
{
_level = 1;
throw new Exception("Level must be in 1 to 3. By default, it becomes 1");
}
else
{
_level = value;
}
}
}
You need to case the Object into a specific Model object something like this
[HttpGet]
public List<Object> Function1()
{
List<Object> result = new List<Object>();
using (DatabaseContext db = new DatabaseContext())
{
//result = db.Object;
result = (from d in db.Object.ToList()
select new Object{
prop1 = d.prop1,
prop2 = d.prop2,
.......
}).ToList();
// ...
return result;
}
}

Foreach() with if statements not affecting variables

I am trying to add an InventoryState to the various products extended from my IProduct interface I created before, but the foreach() statement I made to check the state of the inventory is not changing the default value of Unassigned on the property...
This is the properties for each product object:
public string ProductType
{
get { return "Apple"; }
set { }
}
public double BulkPrice
{
get { return 0.99; }
set { }
}
public double RetailPrice
{
get { return 1.49; }
set { }
}
public int Quantity
{
get { return 50; }
set { }
}
public int MaxQuantity
{
get { return 100; }
set { }
}
public InventoryState Status
{
get { return InventoryState.Unassigned; }
set { }
}
And these are the various declarations and the foreach in question:
public enum InventoryState
{
Full,
Selling,
Stocking,
Empty,
Unassigned
}
public interface IProduct
{
string ProductType { get; set; }
double BulkPrice { get; set; }
double RetailPrice { get; set; }
int Quantity { get; set; }
int MaxQuantity { get; set; }
InventoryState Status { get; set; }
}
public static IProduct[] ProductList =
{
new Apple(),
new Blueberry()
};
foreach (IProduct productName in ProductList) // broken- not being called :(?
{
if (productName.Quantity == productName.MaxQuantity)
{
productName.Status = InventoryState.Full;
return productName.Status;
}
else if (productName.Quantity <= (productName.MaxQuantity * (0.5)))
{
productName.Status = InventoryState.Stocking;
}
else if (productName.Quantity == 0)
{
productName.Status = InventoryState.Empty;
}
else
{
productName.Status = InventoryState.Selling;
}
}
You always do in your automatic properties
get { return "some value";}
Even if you assign a value to it, it will always return "some value" even if the underlying value is different.
Do this for all your properties:
public string ProductType
{
get; set;
} = "Apple";
They will have default value "Apple" but it will get assigned and returned correctly.
Note that auto property default value is only from C# 6.0 onward.
Otherwise you need a private backing field.

How can I update the value of a field in every row of a list?

I have this class:
public class Test
{
public string Id { get; set; }
public int Number { get; set; }
public int DoubleNumber { get; set; }
}
and a list
List<Test> myTestList;
How can I make the value of the field DoubleNumber in myTestList equal to twice the value of Number? Note that I am okay to create another list if that's needed.
If I understand your question correctly:
foreach(Test item in myList) {
item.DoubleNumber = 2*item.Number;
}
Or, if it's ok, just remove the setter and modify the getter to return 2x Number:
public class Test
{
public string Id { get; set; }
public int Number { get; set; }
public int DoubleNumber { get { return 2* this.Number; } } //completely remove setter
}
Or, if you still want to be able to modify DoubleNumber:
public class Test {
private int m_num;
private int m_doubleNum;
public string Id {
get;
set;
}
public int Number {
get {
return this.m_num;
}
set {
this.m_num = value;
this.m_doubleNum = 2 * value; //when Number is set, update m_doubleNum too
}
}
public int DoubleNumber {
get {
return this.m_doubleNum;
}
set {
this.m_doubleNum = value; //allow manual setting of DoubleNumber
//or maybe also modify Number here?
//this.m_num = value / 2;
}
}
}
One way it could be using a foreach statement:
foreach(var item in myTestList)
{
item.DoubleNumber = 2*item.Number;
}
Another way it could be to use LINQ.
var result = myTestList.Select(test => new Test
{
test.Id,
test.Number,
DoubleNumber = 2*test.Number;
})
.ToList();
Among the two ways I would prefer the first one, since it's more clear what you are trying to do and more performant (in the second approach you have to create a new object for each object in myTestList).

Is it possible to have same property with two different names in .NET

I have a property in a class like:
public int ProductID {get;set;}
Is it possible in .NET to make some 'alias' for this property like to give it another name like 'Product_Id'?
So later I can set this property by using:
obj.ProductID = 555;
and
obj.Product_Id = 666;
Sure:
public int Product_Id { get { return ProductID; } set { ProductID = value; } }
private int _prodId;
public int ProductID { get { return _prodId; } set { _prodId = value; } }
public int Product_ID { get { return _prodId; } set { _prodId = value; } }
both ProductID and Product_ID relate to the same member.
Not an alias, but you can just add another property that redirects to that property.
public int ProductID {get;set;}
public int Product_ID
{
get { return ProductID; }
set { ProductID = value;
}

Categories