Stop Resharper from changing "from" to "#from" - c#

I have many methods that have a parameter called from. If I do some refactoring to such a method, R# decides to change the from to #from. But both the compiler and I are happy with from and we don't want this change. I can't find any way to suppress it.
Example method:
public class ObjectA
{
public int J { get; set; }
public int K { get; set; }
}
public class ObjectB
{
public int Y { get; set; }
public int Z { get; set; }
}
public static ObjectB ConvertAtoB(ObjectA from)
{
return from != null
? new ObjectB
{
Y = from.J,
Z = from.K,
}
: null;
}
After invert condition twice on the if statement, the method looks like this:
public static ObjectB ConvertAtoB(ObjectA from)
{
return #from != null
? new ObjectB
{
Y = #from.J,
Z = #from.K,
}
: null;
}
Is there any R# setting that will prevent this?

Related

Comparing record types with LINQ in C#

I am trying to implement record types to make comparing less complex. But I ran into issues comparing records to each other. I expect records to be equal when properties are equal to each other but this isn't the case in my code..
I have a record class called MyAlarm with some properties. It inherits from the interface IAlarm which is empty.
public record MyAlarm : IAlarm
{
public int Prop1 { get; init; }
public int Prop2 { get; init; }
}
A class called VisibleAlarm has the IAlarm as property plus some extra data.
public record VisibleAlarm
{
public IAlarm InternalAlarm { get; init; }
public string Message { get; set; }
}
In a class called AlarmService the VisibleAlarms are listed and updated when needed. This service has a List of visible alarms.
Further in this alarm service the list is checked if an alarm already exists depending on the IAlarm property. I have tried two methods:
public class AlarmService
{
private List<VisibleAlarm> _alarms = new();
// ... Other code that handles alarm stuff
private VisibleAlarm GetExistingAlarm1(IAlarm alarm)
{
return _alarms.FirstOrDefault(a => a.InternalAlarm == alarm);
}
private VisibleAlarm GetExistingAlarm2(IAlarm alarm)
{
foreach (var existingAlarm in _alarms)
{
if (existingAlarm.InternalAlarm == alarm)
{
return existingAlarm;
}
}
}
}
When debugging the code I see that the record properties of the existingAlarm.InternalAlarm and the given alarm match but still the GetExistingAlarm methods return both false. Am i missing something or must I implement a IEqualityComparer because of interface IAlarm?
Cheers
In your line of code:
return _alarms.FirstOrDefault(a => a.InternalAlarm == alarm);
the a.InternalAlarm == alarm is calling operator== rather than object.Equals() to do the comparison.
You can fix this by changing the code to:
return _alarms.FirstOrDefault(a => a.InternalAlarm.Equals(alarm));
The following program demonstrates the difference:
using System;
static class Program
{
public static void Main()
{
MyAlarm ma1 = new MyAlarm { Prop1 = 1, Prop2 = 2 };
MyAlarm ma2 = new MyAlarm { Prop1 = 1, Prop2 = 2 };
VisibleAlarm va1 = new VisibleAlarm { InternalAlarm = ma1, Message = "message" };
VisibleAlarm va2 = new VisibleAlarm { InternalAlarm = ma2, Message = "message" };
Console.WriteLine(ma1 == ma2); // True
Console.WriteLine(va1 == va2); // True
Console.WriteLine(va1.InternalAlarm == va2.InternalAlarm); // False
Console.WriteLine(va1.InternalAlarm.Equals(va2.InternalAlarm)); // True
}
public interface IAlarm
{
int Prop1 { get; }
int Prop2 { get; }
}
public record MyAlarm : IAlarm
{
public int Prop1 { get; init; }
public int Prop2 { get; init; }
}
public record VisibleAlarm
{
public IAlarm InternalAlarm { get; init; }
public string Message { get; set; }
}
}
Output:
True
True
False
True
The reason this isn't working for you is because InternalAlarm is of type IAlarm and not MyAlarm. If you change the type to MyAlarm, you'll get the comparison as true rather than false.
This is because IAlarm does not define an operator== (note: such an operator would be static).

Object attribute Null/Empty check

I have following object and need to check empty/nullability before do something.
Object:
ObjectA = new ObjectA
{
ObjectB = new ObjectB
{
attribute1 = "64072292046",
attribute2 = "",
attribute3 = null
}
}
Code for check nullability and empty
Method I:
private bool checkDataExist(ObjectA myObject)
{
return !myObject.ObjectB.attribute1.IsNullOrWhiteSpace()
|| !myObject.ObjectB.attribute2.IsNullOrWhiteSpace()
|| !myObject.ObjectB.attribute3.IsNullOrWhiteSpace();
}
Method II
private bool checkDataExist(ObjectA myObject)
{
return (myObject.ObjectB.attribute1?? myObject.ObjectB.attribute2 ?? myObject.ObjectB.attribute3) != null;
}
In code readability point of view this is not great. Just wondering any other way to represent this as more human readable?
You can encapsulate that logic into the classes itself and let it decide when it's valid.
public class ObjectA
{
public ObjectB ObjectB { get; set; }
public bool IsValid()
{
if (ObjectB == null) return false;
return ObjectB.IsValid();
}
}
public class ObjectB
{
public string Attribute1 { get; set; }
public string Attribute2 { get; set; }
public string Attribute3 { get; set; }
public bool IsValid()
{
return !string.IsNullOrWhiteSpace(Attribute1)
|| !string.IsNullOrWhiteSpace(Attribute2)
|| !string.IsNullOrWhiteSpace(Attribute3);
}
}
Then you can use it like this
var objA = new ObjectA
{
ObjectB = new ObjectB
{
//init
}
};
if(objA.IsValid())
// do whatever

How to work with object initialization and classes in C#

I have a class
class TestFixture
{
public string a { get; set; }
public int b { get; set; }
public int c { get; set; }
public string d { get; set; }
public string e { get ; set ; }
public int f { get; set; }
public int g { get; set; }
public bool h { get; set; }
public string i { get; set; }
public bool j { get; set; }
public bool k { get; set; }
public TestFixture()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
}
I want to define new TestFixture as SO
new TestFixture { a = "", b = 1, c=2, d="" };
while the rest of properties should be auto defined as it written in constructor.
Is it possible ?
Yes, this is possible. Using an object initializer does not skip calling the constructor.
TestFixture fixture = new TestFixture() // or just new TestFixture { ... }
{
a = "",
b = 1,
c = 2,
d = ""
};
This will call the constructor you've defined and then set a, b, c, and d in your object initializer.
Pop a breakpoint in your constructor and run your debugger. This is should show you how and when things in your code are called.
Debugging in Visual Studio
Refactored:
public class TestFixture
{
public string a { get; set; }
public int b { get; set; }
public int c { get; set; }
public string d { get; set; }
// dosomething should check for null strings
public string e { get { return dosomething(a, b); } }
public int f { get; set; }
public int g { get; set; }
public bool h
{
get { return TestName.Equals("1") && b.Equals("2") ? 1000 : 1; }
}
public string i { get; set; }
public bool j { get { return a != null && a.Equals("FOT"); } }
public bool k { get; set; }
public TestFixture(string a, int b, int c, string d)
: this()
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public TestFixture()
{
f = false;
g = DateTime.Now.ToString("yyMMddhhmmss");
i = 10000000;
k = false;
}
}
#hunter's answer is correct, you can use object initializer syntax, and those properties will be set after your constructor runs. However, I'd like to point out some flaws you may have with your code
public TestFixture()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
This code does not set a or b, but you have things that depend on their values (e, g, j). Object initializer syntax is not going to be useful here, you have to have proper defaults for these values if other values in the constructor will depend upon them.
As an example, when you write var obj = new Bar() { A = "foo" };, that will expand to
var obj = new Bar(); // constructor runs
obj.A = "Foo"; // a is set
Clearly, the code in the constructor that looks at A will not see the value "Foo". If you need it to see this value, object initialization strategy is not going to help. You need a constructor overload that takes the value to be stored in A.
var obj = new Bar("Foo");
If I understand you right, you would like to the a, b, c and d properties to be initialized with the given values before the constructor runs. Unfortunately, that is not possible this way, because the default constructor always runs before the object intializers.
I advise you to do something like this instead:
class TestFixture
{
//... properties
public TestFixture()
{
this.init();
}
public TestFixture(string a, int b, int c, string d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.init();
}
private void init()
{
e= dosomething(a, b);
f= false;
g = DateTime.Now.ToString("yyMMddhhmmss");
h= TestName.Equals("1") && b.Equals("2") ? 1000 : 1;
i= 10000000;
j= a.Equals("FOT");
k = false;
}
}
This way you can init the a, b, c and d properties before the other initializer code runs.

Get the index in a multidimensional class

Sorry for the title i will put here an example of what i want to accomplish:
namespace mdclass
{
class pClass
{
static void Main()
{
tiles<int> tl = new tiles<int>();
tl[0].X = 0;
}
}
class tiles<T> : List<T>
{
public int X
{
//get/set the X-coordonate
}
public int Y
{
//get/set the Y-coordonate
}
}
}
how can i transfer the [0] from the tl[0] in the public int X and work with it?
Create a class for x and y coordinates:
public sealed class Point {
public int X { get; set; }
public int Y { get; set; }
}
Use the Point class to store the coordinates into the list:
public sealed class Program {
public static void Main() {
var tiles = new List<Point>();
tiles.Add(new Point { X = 5, Y = 10 });
tiles[0].X = 15;
}
}
Could you not just make tl public?
Then myInt = mypClass.tl[0].X
A data heirachy like this might work for you (no time to add actual code, sorry!). Then you could implement appropriate getters and setters.
Public class Grid {
List<Row>
}
Public class Row{
List<Point>
}
Public Class Point{
public int X { get; set; }
public int Y { get; set; }
}

ordering generic list by size property

Hi I have had to use interfaces before but ive been told i need to implement icomparable in this instance. see below:
internal class doorItem : IComparable
{
public int CompareTo(doorItem other)
{
// The temperature comparison depends on the comparison of the
// the underlying Double values. Because the CompareTo method is
// strongly typed, it is not necessary to test for the correct
// object type.
return GetNumber(productSize).CompareTo(GetNumber(other.productSize));
}
public string variations { get; set; }
public double pricerange { get; set; }
public string viewDetailsLink { get; set; }
public string height { get; set; }
public string width { get; set; }
public string productSize { get; set; }
public string productImage { get; set; }
public int countItemsOnSale { get; set; }
public string optionFor35Product { get; set; }
private int GetNumber(string str)
{
//this method gets the int out of the string
int length = str.Length;
string output = String.Empty;
int test = 0;
bool err = false;
for (int i = 0; i <= length; i++)
{
try
{
test = Convert.ToInt32(str.Substring(i, 1));
}
catch
{
err = true;
}
if (!err)
output += str.Substring(i, 1);
else
break;
}
return Convert.ToInt32(output);
}
}
above is the class i have created, door sizes are returned like this: 4dr, 5dr, 6dr etc.. then the getnumber method gets the int out of the string.
i have a generic list in of my custom class in the main method like this:
List<doorItem> d = new List<doorItem>();
i cant work out how to order this list by door size.... PLEASE HELP
It's easiest to do this using LINQ. Then you don't even need to implement IComparable.
var sortedList = doorList.OrderBy( d => d.GetNumber(d.productSize ).ToList();
And make GetNumber public inside the doorItem class.
I don't know if performance is important, but that method for getting the number is pretty horrible, exceptions should only be used in exceptional circumstances! Suggest something like this
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if (Char.IsNumber(c))
{
sb.append(c);
}
}
return Convert.ToInt32(sb.ToString());
For sorting you can do what stecya has suggested, or you could convert this method to a property and sort directly.
public int Size
{
get
{
return GetNumber(this.productSize);
}
}
...
d.OrderBy(x=>x.Size);

Categories

Resources