Code1
public class Human
{
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
}
Code2
public class Here
{
public static void Main(String[] args)
{
Human hm = new Human();
hm.Name = "Bill";
hm.Gender = "Male";
hm.Age = 20;
}
}
Now, I'd like to use the variable "hm" as String where hm will return the Name property... something like:
string person = hm;
Console.WriteLine(person + " has greeted you!");
What will I do? Should I make an Extension or something?
I overridden the ToString() method, and yes, it works on Console.WriteLine()
but now, I want to store it as string in a string variable
string person = hm;
Console.WriteLine(person);
and I get this
Cannot implicitly convert type 'Human' to 'string'
I also want to use it in my VB.NET program, but it gives me this error when I concatenate it:
Operator '&' is not defined for types 'String' and 'Human'
You can declare an implicit conversion from your type to string using operator overloading. But it's a bad idea. I suggest you to override ToString method in your class instead, then you can just output it like this:
Console.WriteLine(hm + " has greeted you!");
There is also a good documentation on how to override ToString method
How To: Override the ToString Method (C# Programming Guide)
An implicit convention by adding the following to the Human class would work
public static implicit operator string(Human h)
{
return h.Name;
}
Although i think the best way is to override the ToString Method like so
public override string ToString()
{
return Name;
}
You could override the ToString method:
public class Human
{
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
public override string ToString()
{
return Name;
}
}
Override ToString() method.
public class Human
{
public override ToString() { return Name }
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
}
Your code would then look like this:
Console.WriteLine(hm + " has greeted you!");
vb.net answer:
As state by others, you need to define a conversion operator. If you want to support string concatenation then you also need to define the & operator.
Public Class Human
Public Property Name As String
Public Shared Widening Operator CType(value As Human) As String
Return value.Name
End Operator
Public Shared Operator &(left As Human, right As String) As String
Return (left.Name & right)
End Operator
Public Shared Operator &(left As String, right As Human) As String
Return (left & right.Name)
End Operator
Public Overrides Function ToString() As String
Return Me.Name
End Function
End Class
Related
So lets say i have this class:
public class LogLine
{
public string Text { get; set; }
public string this[object o] { get => Text; set => Text = value; }
}
And then I have this other one:
public class Logger
{
public LogLine WriteLine(string _text, LogLine v)
{
LogLine obj = v;
obj[null] = _text;
return obj;
}
}
And everything works as inteded, but I would like to do something like
obj = _text;
instead of
obj[null] = _text;
So the final question would be: Is there a way to do that?
I know I could always do
obj.Text = _text;
So I also would like to know if I am just asking about something like bad practice or so. I'm learning n.n'
You can provide an implicit conversion operator from string to LogLine:
public class LogLine
{
public string Text { get; set; }
public static implicit operator LogLine(string input)
{
return new LogLine{ Text = input };
}
}
Now this is allowed:
obj = _text;
Is it possible to add custom attribute on Class, that override all empty string properties? Something like this:
[DefaultValueForEmptyString(Text="N/A")]
public class PersonsDTO
{
public string Name { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
}
public class DefaultValueForEmptyString
{
public static void MapProperties(object Properties, string text)
{
foreach (var property in Properties)
{
if(string.IsNullOrEmpty(property))
{
property = text // "N/A in this case
}
}
}
}
To resolve a similar problem ages ago I implemented an extension to handle this :
public static string ValueOrDefault(this string value)
{
return string.IsNullOrWhiteSpace(value) ? "N/A" : value;
}
Now you can use this on all your string properties :
var person = new PersonsDTO();
//Prints N/A
Console.WriteLine(person.Name.ValueOrDefault());
That's not really impressive but the job is done.
Another option would be to make a custom string class that implicitly converts from your custom class to string and from a string to your custom class. It's a bit heavy handed, but so is making a custom attribute class.
I made a .NET fiddle showing an example of this here
A copy of the code is below in case .NET fiddle goes away.
using System;
public class DefaultString
{
private const string _default = "N/A";
public DefaultString(string normal)
{
Value = normal;
}
private string _value = _default;
public string Value
{
get
{
return _value;
}
set
{
if (String.IsNullOrEmpty(value))
_value = _default;
else
_value = value;
}
}
public bool IsDefault()
{
return Value == _default;
}
public override string ToString()
{
return Value;
}
public static implicit operator string(DefaultString defaultString)
{
if (defaultString == null)
return _default;
return defaultString.ToString();
}
public static implicit operator DefaultString(string normal)
{
return new DefaultString(normal);
}
}
public class Program
{
public static void Main()
{
DefaultString nullDefault = null;
DefaultString nullConstructorDefault = new DefaultString(null);
DefaultString emptyDefault = String.Empty;
DefaultString emptyConstructorDefault = new DefaultString(String.Empty);
DefaultString abcDefault = "abc";
DefaultString abcConstructorDefault = new DefaultString("abcConstructor");
Console.WriteLine("Default string assigned to null: " + nullDefault);
Console.WriteLine("Default string constructed with null: " + nullConstructorDefault);
Console.WriteLine("Default string assigned empty string: " + emptyDefault);
Console.WriteLine("Default string constructed with empty string: " + emptyConstructorDefault);
Console.WriteLine("Default string assigned \"abc\": " + abcDefault);
Console.WriteLine("Default string constructed with \"abcConstructor\": " + abcConstructorDefault);
}
}
The output should be:
Default string assigned to null: N/A
Default string constructed with null: N/A
Default string assigned empty string: N/A
Default string constructed with empty string: N/A
Default string assigned "abc": abc
Default string constructed with "abcConstructor": abcConstructor
I am new to C# and was asked to create two class definitions (customer and order) using partial code and with the suggested class names, methods, contructors and following an example. I am not sure why I am getting so many errors when I build/debug?
After this is finished, I need to create another program that builds onto this one. Our instructor also asked us not to use validation...
Some of my most common errors are:
expected: ; (in a place in my code where I believe there should not be a semi-colon and
Error "Expected class, delegate, enum, interface, or struct.
Here is my code:
public class clsOrder
{
//declare class variables
protected string cstrDescription;
protected int cintQuantity;
protected decimal cdecPrice;
protected decimal cdecExtendedPrice;
//shared variables
static decimal cdecTotalPrice;
static int cintTotalCount;
//declare constructors
public clsOrder();
}
public clsOrde r(string strDescription,
int intQuantity, decimal decPrice)
}
//declare property methods
{
this.Description = string strDescription;
this.Quantity = int intQuantity;
this.Price = decimal decPrice;
//declare read-only properties
public decimal ExtendedPrice
}
public string Description
{
get
{
return strDescription;
}
set
{
strDescription = value;
}
}
public int Quantity
{
get
{
return intQuantity;
}
set
{
intQuantity = value;
}
}
public decimal Price
{
get
{
return decPrice;
}
set
{
decPrice = value;
}
}
get
{
return cdecExtendedPrice;
}
}
//declare Shared (static) ReadOnly Properites
public static decimal TotalPrice
{
get
{
return cdecTotalPrice;
}
}
public static int TotalCount
{
get
{
return cintTotalCount;
}
}
//declare supporting methods
public void calcExtendedPrice()
{
cdecExtendedPrice = cintQuantity * cdecPrice;
}
public void accumulateTotals()
{
cdecTotalPrice += cdecExtendedPrice;
cintTotalCount += 1;
}
public static void resetTotals()
{
cdecTotalPrice = 0;
cintTotalCount = 0;
}
}//end of Class
}//end of namespace
And
public class clsCustomer
{
//declare class variables
private string cstrName;
private string cstrStreet;
private string cstrCity;
private string cstrState;
private string cstrZip;
//declare constructors
public class clsCustomer()
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
}
//declare property methods
{
this.Name = cstrName;
this.Street = cstrStreet;
this.City = cstrCity;
this.State = cstrState;
this.Zip = cstrZip;
}
public string Name
{
get
{
return cstrName;
}
set
{
cstrName = value;
}
}
public string Street
{
get
{
return cstrStreet;
}
set
{
cstrStreet = value;
}
}
public string City
{
get
{
return cstrCity;
}
set
{
cstrCity = value;
}
}
public string State
{
get
{
return cstrState;
}
set
{
cstrState = value;
}
}
public string Zip
{
get
{
return cstrZip;
}
set
{
cstringZip = value;
}
}
Any help would be very much appreciated, thank you.
I want to create a class that can set multiple value and not delete the old one that was set already, instead add it and the old value. Here is my sample.
myClass myCls = new myClass();
myCls.setString = "My first string!";
myCls.setString = "My second string!";
myCls.setString = "My third string!";
string printMe = myCls.getString();
Console.WriteLine(printMe);
And when it will output something like;
//My first string!My second string!My third string!
One way to do it would be to have a new property on your myClass
public class myClass
{
private string _setString;
public string setString
{
get
{
return _setString;
}
set
{
AuditTrail += value;
_setString = value;
}
}
public string AuditTrail{get;set;}
}
Then in your main method you'd put:
Console.WriteLine(AuditTrail);
You can try with this class:
public class ValueKeeper {
private List<object> values;
public object Value {
get { return ToString(); }
set { values.Add(value); }
}
public ValueKeeper() {
values = new ArrayList<object>();
}
public override string ToString() {
string result = String.Empty;
foreach(object value in values) result += value.ToString();
return result;
}
}
It can be improved of course, but it would satisfy your needs.
Example
ValueKeeper valueKeeper = new ValueKeeper();
valueKeeper.Value = 1;
valueKeeper.Value = "This is a string";
valueKeeper.Value = someCustomObject;
string str = valueKeeper.Value;
Console.WriteLine(str); //PRINTS OUT "1This is a stringxxxxx"
//Where "xxxx" is the string representation of the custom object
You can create class like this.
class MyClass
{
private string myString;
public string MyString
{
get
{
return myString;
}
set
{
myString += value;
}
}
}
In you Program you can use like this
MyClass c = new MyClass();
c.MyString = "String 1";
c.MyString = "String 2";
Console.WriteLine(c.MyString);
This seems like an odd request but it can be done!
class myClass
{
//Properties
private string privateString;
//Constructor
public myClass()
{
}
//Methods
public void setString(string val)
{
privateString += val;
}
public string getString()
{
return privateString;
}
}
string _entry;
public string Entry
{
get { return _entry; }
set { _entry += value; }
}
I am new to Asp .net C#. i have question about objects and inheritance.
if i have parent class (Base-Table) that have 2 child classes (Credit-Card-Table , Bank-Account-Table) i have fun. in another class that take an object from the base-table class.
my problem is i want to know if the Base-table is Credit-card or Bank-account ?!
class BaseTable
{
string date;
public string Date
{
get { return date; }
set { date = value; }
}
string description;
public string Description
{
get { return description; }
set { description = value; }
}
}
class CreditCardTable:BaseTable
{
string Amount;
public string amount
{
get { return Amount; }
set { Amount = value; }
}
string Type;
public string type
{
get { return Type; }
set { Type = value; }
}
}
class BankAccountTable:BaseTable
{
string Refr;
public string Ref
{
get { return Refr; }
set { Refr = value; }
}
string debit;
public string Debit
{
get { return debit; }
set { debit = value; }
}
string credit;
public string Credit
{
get { return credit; }
set { credit = value; }
}
}
3 options:
use is, as or GetType() to explicitly check the type of an instance you have been given, to test it against some known types
if(obj is CreditCardTable) {...} else ...
add a virtual or abstract method to the base-type, and use that instead of ever having to worry about which it is (since it will automatically invoke the most derived override)
obj.SomeMethod();
add a discriminator - perhaps a virtual enum property to the BaseTable which all derived types return a different value from, and switch on that discriminator:
switch(obj.Type) { ... }