Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize public properties of a class using a different type in C#?

Tags:

In Java, I can have an object like this:

public class MyObject {      private Date date;      public Date getDate() {         return date;     }      public void setDate(Date date) {         this.date = date;     }      public void setDate(String date) {         this.date = parseDateString(date);     }      private Date parseDateString(String date) {         // do magic here         return dateObj;     }  } 

This is nice, because I have one getter for my properties, and multiple setters. I can set the "date" property by passing in either a Date object, or a String, and let the class figure it out.

In C# it looks like things are a little different. I can do this:

public class MyObject {     public DateTime Date { get; set; } } 

The shorthand here is obviously optimal. However, I'm not sure if there's any built-in way to overload the setter to accept multiple types. I realize I could create a separate public method to set the value, but that would sacrifice the ability to use object initializers.

Is there any way to directly overload the setter on public properties for C#? Or is this just a language limitation, and it can't be done?

like image 745
soapergem Avatar asked Apr 03 '15 18:04

soapergem


People also ask

What is getter setter in C#?

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.

Why we use get set property in C#?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.


1 Answers

All other answers are correct... but if you insist, you can do it in several ways:

  1. Use a second property with just a setter:

    public string DateText { set { Date = ParseDateString(value); } } 

    Avoid this if possible, it only adds confusion :-)

  2. Use methods instead of properties (same as you do in Java). Methods can be overloaded. This should be the most recommended way.

  3. Use a custom class (instead of DateTime) and provide implicit conversions between DateTime, string, and your class. Not recommended unless you are going to use this everywhere else.

  4. Change the property to object and provide your conversions in the setter: please don't do this

like image 170
Jcl Avatar answered Sep 30 '22 16:09

Jcl