I need to convert the following code which is in C# 6.0 to a lower version which works in .NET framework 4.5.
public ImageCollection Strokes { get; } = new ImageCollection(); //C# 6.0
How do i convert this?
Tried the below code but had few issues in the application.
public ImageCollection Strokes
{ get { return new ImageCollection(); } } //< 6.0
Kindly help. Also is there any way to convert these? Often i get solutions in 6.0 which i have to downgrade.
Its not the same.
In the first example you have a property which will be instantiated through the constructor.
In the second example you return a new instance every time you access the property.
The correct refactor looks like this:
public ImageCollection Strokes
{
get; private set;
}
public constructor()
{
Strokes = new ImageCollection();
}
You are going to have to assign the property in your constructor.
Option 1 - A property with a private setter:
class Example
{
public ImageCollection Strokes { get; private set; }
public Example()
{
Strokes = new ImageCollection();
}
}
Option 2 - A property with a getter only, backed by a private readonly field:
class Example
{
public ImageCollection Strokes { get { return _strokes; } }
private readonly ImageCollection _strokes;
public Example()
{
_strokes = new ImageCollection();
}
}
Option 3 - Like option 2, but assigning the field inline instead of in the constructor:
class Example
{
public ImageCollection Strokes { get { return _strokes; } }
private readonly ImageCollection _strokes = new ImageCollection();
}
You could create a private field that the getter uses:
class MyClass
{
private ImageCollection _strokes = new ImageCollection();
public ImageCollection Strokes { get { return _strokes } }
}
Or you could initialize it in the constructor.
class MyClass
{
public ImageCollection Strokes { get; private set; }
public MyClass()
{
Strokes = new ImageCollection();
}
}
Just remember to initialize it in all constructors of the class, or at least have your other constructors call a constructor that does.
The problem with your solution is that it returns a new instance of ImageCollection each time get is called. This produces multiple that have nothing to do with each other. Changing one will not change the rest.
I dont know what issues you arr facing but change code like below
your code always creating the new object , but 6.0 one time initialization
Try
var imgCollection = new ImageCollection();
public ImageCollection Strokes
{ get { return imgCollection; } } //< 6.0
Related
I want to have a class, that stores all "allowed languages" in a list. Code party should be able to modify the list. But on first usage, the list should be "initialized" with some default values.
I have the following class:
public class ApiLanguages
{
public static List<string> AllowedLanguages { get; set; }
public ApiLanguages()
{
AllowedLanguages.Add("de");
//AllowedLanguages.Add("en");
//AllowedLanguages.Add("es");
//AllowedLanguages.Add("fr");
//AllowedLanguages.Add("it");
}
}
When I access the class now in code with
foreach (var language in ApiLanguages.AllowedLanguages)
{
// do something here...
}
the ApiLanguages.AllowedLanguages is null. But I expect one entry ("de"). What I am doing wrong here?
public ApiLanguages() is an instance constructor. It runs only (and every time) when you create a new instance of ApiLanguages (via new ApiLanguages()). It's purpose is to initialize instance variables, not static ones. You usually shouldn't initialize static properties or fields in an instance constructor.
You need to use the static constructor to initialize the static list like this:
public class ApiLanguages
{
public static List<string> AllowedLanguages { get; set; }
static ApiLanguages()
{
AllowedLanguages = new List<string>();
AllowedLanguages.Add("de");
//...
}
}
You can make your constructor static as well, but I prefer lazy loading. By this you will not populate list again and again whenever object is created of ApiLanguages,
public class ApiLanguages
{
private static IEnumerable<string> _allowedLanguages;
public static IEnumerable<string> AllowedLanguages
{
get
{
return _allowedLangues ?? (_allowedLangues = new List<string>{ "EN", "AR"});
}
}
}
You should initialize AllowedLanguages with new instance of List<string> first. You can do it with initializers for auto-properties in c# 6.0 or in the static constructor for older versions of c#.
public class ApiLanguages
{
// c# 6.0 syntax
public static List<string> AllowedLanguages { get; set; } = new List<string>();
static ApiLanguages()
{
// c# < 6.0 (old style) syntax
AllowedLanguages = new List<string>();
}
public ApiLanguages()
{
AllowedLanguages.Add("de");
}
}
Also I'm sure that you no need to add new values to the list for each instance of ApiLanguages class then you should move AllowedLanguages.Add(...) to the static constructor too. And you can join object creation and initialization to a single line of code:
public static List<string> AllowedLanguages { get; set; } = new List<string>() { "de", "en", "ru" };
I'm just wondering if there's an automated way to generate constructors with every possible combination of the parameters you might need.
I have a ctor with 4 parameters, but I want to provide overloads where a developer could pass in a single param, or two or three. By hand I've been writing every possible combination and passing defaults to the 4 parameter one. I also need to then introduce two more "full" prototypes ( with a fifth ), then create all the possible combinations for those as well, so I need loads of ctor overloads to cover all combinations.
I'd like to manually write the three full ctors, then be able to generate the combinations with a context menu click. I haven't seen an option like this in Resharper. Anyone know if there's an existing solution out there already?
If you need a lot of constructor parameters, rather than struggling with the explosion of possible permutations, consider creating an "options" class that has sensible defaults:
public class FooOptions
{
public FooOptions()
{
MaintenanceInterval = TimeSpan.FromSeconds(30);
MaximumIdleTime = TimeSpan.FromMinutes(5);
}
public TimeSpan MaintenanceInterval { get; set; }
public TimeSpan MaximumIdleTime { get; set; }
//etc...
}
then
class Foo
{
public Foo():this(new FooOptions())
{
}
public Foo(FooOptions opts)
{
//...
}
}
This situation would be a perfect fit for the Builder pattern.
For example, if the class Foo can have any combination of a String, an int and a Bar:
public class Foo
{
public string MyString { get; set; }
public int MyInt { get; set; }
public Bar MyBar { get; set; }
}
Instead of adding a constructor with every possibility, make a Builder. Here's an example of a simple fluent implementation:
public class FooBuilder
{
private Foo foo = new Foo();
public FooBuilder WithString(String someString)
{
foo.MyString = someString;
return this;
}
public FooBuilder WithInt(int someInt)
{
foo.MyInt = someInt;
return this;
}
public FooBuilder WithBar(Bar someBar)
{
foo.MyBar = someBar;
return this;
}
public Foo Build()
{
return foo;
}
}
which can be used like this:
Foo foo = new FooBuilder().WithString("abc").WithInt(3).Build();
This eliminates completely the need for an exponential number of constructors.
Don't need multiple constructor overloads - try using optional/default parameters. Relevant link: https://msdn.microsoft.com/en-us/library/dd264739.aspx
Example code:
class Program
{
static void Main(string[] args)
{
var defaultMonster = new Monster();
var archerMonster = new Monster("crossbow");
var knightMonster = new Monster("broadsword", "plate mail");
var wizardMonster = new Monster(armor: "wizard robe", magicItem: "wand");
Console.WriteLine(defaultMonster);
Console.WriteLine(archerMonster);
Console.WriteLine(knightMonster);
Console.WriteLine(wizardMonster);
}
}
class Monster
{
private readonly string _weapon;
private readonly string _armor;
private readonly string _magicItem;
public Monster(string weapon = "scimitar", string armor = "leather", string magicItem = "nothing")
{
_weapon = weapon;
_armor = armor;
_magicItem = magicItem;
}
public override string ToString()
{
return string.Format("Monster armed with {0}, wearing {1}, carrying {2}", _weapon, _armor, _magicItem);
}
}
I've I really weird problem with my WPF / C# application. I've got a property which returns another property. Now I make a variable and set it to one of these properties. If I now change the value by binding, the variable is also changed.
To simplify it, here's the code:
Here's the first property:
public MainDataObject CmObj_Temp { get; set; }
Which is used here:
public MainDataObject CmObj_MainData {
get {
return TemporaryDataStore.CmObj_Temp;
}
set {
TemporaryDataStore.CmObj_Temp = value;
this.RaisePropertyChanged(() => this.CmObj_MainData);
}
}
From which I set a variable here:
CmObj_Backup = TemporaryDataStore.CmObj_Temp;
or also like this (makes no different):
CmObj_Backup = ((VM)this.DataContext).CmObj_MainData;
And also use for binding here:
<TextBox Text="{Binding CmObj_MainData.Str_Internnr, Mode=TwoWay}"/>
Now if I change the text of the Textbox it also changes it here:
CmObj_Backup.Str_Internnr);
Can someone tell my why?
How can I change that?
Thx
This is an smaller form of my code:
public class DataObject
{
public string Str_Test1 {get; set;}
public string Str_Test2 {get; set;}
// --> Much more properties
}
public static class TempData
{
public static DataObject DObj1 {get;set;}
}
public class ViewModel
{
public DataObject DObj2 {
get {
return TempData.DObj1;
}
set {
TempData.DataObjet.DObj1 = value;
this.RaisePropertyChanged(() => this.DObj2);
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
var VM = new ViewModel();
this.DataContext = VM;
}
public void SomeWhereInTheSoftware()
{
((ViewModel)this.DataContext).DObj2.Str_Test1 = "Before";
ObjBackup = ((ViewModel)this.DataContext).DObj2;
((ViewModel)this.DataContext).DObj2.Str_Test1 = "After";
// --> Here is ObjBackup.Str_Test1 also "After"!!
}
}
If you would show full code blocks instead of randomly chosen lines of code it would be easier to follow. Your example isnt very clear to me.
However, I think you are having an issue because you think you are have 2 copies of an object when you really have 1. Objects are kept as reference so if you create a MainObject and a CopyObject you cant just set CopyObject equal to MainObject and expect to have a real copy.
Again, I could be way off given I dont understand your question fully but for example:
class A {
public string Message { get; set; }
}
public static void Main()
{
A mainData = new A();
mainData.Message = "Main Data Message";
A backupData = mainData;
backupData.Message = "Backup Data Message";
Console.WriteLine(mainData.Message);
// Prints Backup Data Message
Console.WriteLine(backupData.Message);
// Prints Backup Data Message
}
Edit: cloning as a solution
As Viv mentioned in the comment the solution to your problem would be to clone the object, which creates an actual copy of the object as opposed to a reference to the object.
you would update class A in this way:
class A : ICloneable
{
public string Message { get; set; }
public override object Clone()
{
A clone = new A();
clone.Message = this.Message;
return clone;
}
}
reference to ICloneable is here http://msdn.microsoft.com/en-us/library/system.icloneable.aspx
I have the following class but I can't seem to get the desired results with C#.
public class AppOsType {
public static class IOS {
public static int IOS()
{
return 100;
}
public static string ToString()
{
return "iOS";
}
}
... // additional values
}
I want to get the following results:
AppOsType.IOS // returns 100
AppOsType.IOS.ToString() // returns "iOS"
But I'm getting an error saying AppOsType.IOS is a type when i do the following:
Assert.AreEqual(100, AppOsType.IOS);
What am I missing?
Edit: left out static.
Not sure why all the static and inner class stuff is needed for, why don't you keep it simple and define an enum:
public enum AppOsType
{
IOS = 100
}
Then use
var ios = AppOsType.IOS;
var number = (int)ios;
var name = ios.ToString();
If you need to return a translated string based on enum, you could add a dictionary:
var translations = new Dictionary<AppOsType, string>()
{
{ AppOsType.IOS, "iOs" }
}
and then
var ios = AppOsType.IOS;
var number = (int)ios;
var name = translations[ios];
If you really need this nested static class inside the AppOsType class then you need to change something because a method cannot have the same name of the class and a constructor cannot return values. (Think to the fact as if the return value of the constructor is already defined to be the instance of the class)
void Main()
{
Console.WriteLine(AppOsType.IOS.Version);
Console.WriteLine(AppOsType.IOS.ToString());
}
public class AppOsType
{
// .... other members here ?? ...
public static class IOS
{
public static readonly int Version;
static IOS()
{
// In the static constructor you could set the readonly
// static property
Version = 100;
}
public static string ToString()
{
return "iOS";
}
}
}
Its becaus IOS is a class. AppsOsType.IOS points to the static class. If your Method public int IOS() would be static, you can access it using AppOsType.IOS.IOS()
If you don't want an enum for some reason, to make it work with desired syntax, you need a public property (not a ctor or method) :
public class AppOsType {
public static class IOS {
public static int IOS
{
get { return 100; }
}
public static string ToString()
{
return "iOS";
}
}
}
You are using the same name IOS so change this
AppOsType.IOS // returns 100 [error]
to
AppOsType.IOS.IOS // might returns 100
I've been reviewing the PRISM toolkit and I find many examples where they declare a public property with empty getters/setters yet they can still set the property of the instantiated class. How/why is this possible?
public class ShellPresenter
{
public ShellPresenter(IShellView view)
{
View = view;
}
public IShellView View { get; private set; }
}
//calling code
ShellPresenter sp = new ShellPresenter();
//Why is this allowed?
sp.View = someView;
This is a new feature in C# 3.0.
http://msdn.microsoft.com/en-us/library/bb384054.aspx
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.
They're using C# auto properties. It's a convenience whereby the compiler generates the backing field for you. private set means that the property is read-only from outside the class. So, if sp.View = someView; is being used outside of the class then it will result in a compiler error.
Decompiling your ShellPresenter with the Red Gate .NET Reflector
public class ShellPresenter
{
// Fields
[CompilerGenerated]
private IShellView <View>k__BackingField;
// Methods
public ShellPresenter(IShellView view)
{
this.View = view;
}
// Properties
public IShellView View
{
[CompilerGenerated]
get
{
return this.<View>k__BackingField;
}
[CompilerGenerated]
private set
{
this.<View>k__BackingField = value;
}
}
}
What you posted is not allowed unless the object is being set within the class itself. Here's a code sample of what is and is not allowed.
public interface IShellView
{
}
public class View:IShellView
{
}
//public class SomeOtherClass
//{
// static void Main()
// {
// IShellView someView = new View();
// //calling code
// ShellPresenter sp = new ShellPresenter();
// //Why is this allowed?
// sp.View = someView;//setting a private set outside the ShellPresenter class is NOT allowed.
// }
//}
public class ShellPresenter
{
public ShellPresenter()
{
}
public ShellPresenter(IShellView view)
{
View = view;
}
static void Main()
{
IShellView someView = new View();
//calling code
ShellPresenter sp = new ShellPresenter();
//Why is this allowed?
sp.View = someView;//because now its within the class
}
public IShellView View { get; private set; }
}
C# compiler generates backend field for you. This syntax was introduced for anonymous types support (like new { A = 1, B = "foo" } )