__dil__
__dil__
Explore posts from servers
CC#
Created by __dil__ on 11/3/2023 in #help
❔ Rider's "cleanup on save" adds named parameters seemingly at random
I have a function with this signature:
public bool GetTelemetryData(
ref int serialNum,
out int batteryPercentage,
out int distanceDrivenInMeters
) { ... }
public bool GetTelemetryData(
ref int serialNum,
out int batteryPercentage,
out int distanceDrivenInMeters
) { ... }
Then, when I call it like so:
public string GetBatteryUsagePerMeter(int serialNum)
{
var validSerialNum = _car.GetTelemetryData(
ref serialNum, // <-- It happens here
out var batteryPercentage,
out var distanceDrivenInMeters
);

...
}
public string GetBatteryUsagePerMeter(int serialNum)
{
var validSerialNum = _car.GetTelemetryData(
ref serialNum, // <-- It happens here
out var batteryPercentage,
out var distanceDrivenInMeters
);

...
}
Rider will automatically add a named parameter like serialNum: ref serialNum,. It only adds it to this particular parameter. I don't understand why? I there's a particular reason I'm happy to keep it as is, but it just seems random. Anybody knows what's happening?
3 replies
CC#
Created by __dil__ on 10/28/2023 in #help
❔ How to make Rider format and cleanup code by default?
Everytime I create a new solution, I have to go into the options and enable "actions on save" -> "format and cleanup". How can I change it so it's there by default when I create a new solution?
18 replies
CC#
Created by __dil__ on 10/24/2023 in #help
❔ Prevent Rider from removing "redundant" named arguments.
As per the title, I have constructors which take a lot of arguments. I use the constructors to manually instantiate a bunch of stuff in a list, like this:
{
new ...(
// Lots of arguments here
),
new ...(
// Lots of arguments here
),
// etc...
}
{
new ...(
// Lots of arguments here
),
new ...(
// Lots of arguments here
),
// etc...
}
A lot of these arguments have the same type and it's possible that I might add/remove some arguments as the project evolves. So, for the sake of readability and not breaking code when I change the constructors, I'd like all the arguments to be named. Unfortunately, Rider removes the annotations that it thinks are redundant. That's usually fine, but in this specific instance I want full clarity and consistency. Any way I can achieve this without globally disabling code cleanup?
2 replies
CC#
Created by __dil__ on 10/17/2023 in #help
❔ [Avalonia] Basic question regarding subclassing
Let's say I have some types like so:
public abstract class Foo {}

public class FooA: Foo {}

public class FooB: Foo
{
public string Name { get; }
public int age { get; }
}
public abstract class Foo {}

public class FooA: Foo {}

public class FooB: Foo
{
public string Name { get; }
public int age { get; }
}
I'd like to display a List<Foo> where FooAs and FooBs would be displayed completely differently. Just as a random example, FooA would simply display "This is a FooA" with a red background while FooB would display "This is a FooB with name '...' and age '...' " in a blue background. You get the idea. The way I envision this is that FooA and FooB would themselves define how they should be displayed. I would be really grateful if someone could break this down to me. Bonus points if there's a working example.
60 replies
CC#
Created by __dil__ on 10/17/2023 in #help
❔ Design question
Hi! I'm a beginner and I'm having trouble finding a decent design for this toy application I'm making. So, at a high level, I have a list of items, and I'd like to let the user filter the items and only display the relevant ones. So far so good, but the complexity comes from the fact that the items in my case come in many variants (let's call them A, B, C, etc. for the sake of the discussion). Item variants are definitely related in terms of the domain, but they are fairly unrelated when it comes to the data itself. So, A might have a little bit in common with C, B might have a little in common with A, etc. There's very little that is common to all the variants. So, all the items should live in the same list to be filtered, but the filter might refer to a field that doesn't even exist on a specific variant (in that case it should be excluded). Furthermore, once the items have been filtered, it should be possible to select a particular item and see all the data specific to that variant. So I need some sort of downcasting mechanism. I'm sorry if this sounds confusing, well I am confused :/
14 replies
CC#
Created by __dil__ on 10/13/2023 in #help
❔ Dependency Injection
Disclaimer: I come from a low-level language, never did Java and very new in C#. I started to read the Avalonia UI MVVM tutorial, and it mentioned that usually you'd use DI to avoid coupling the model and the viewmodel. This got me curious about what exactly is DI. My understanding is that you have a service that uses a dependency. Instead of using the dependency directly, you make the service use an interface for that service, and provide an instance of that interface somehow. So, the "replace concrete type with interface" I get. My main confusion is about how to provide the instance. From what I read, it's either 1) passing a concrete type instance to a constructor that expects the interface type. Or 2) Something involving "frameworks and "automatic registration". Option 1) is pretty intuitive, not much to be confused about here, but option 2) is complete gibberish to me.
57 replies
CC#
Created by __dil__ on 10/9/2023 in #help
❔ ✅ Struct equality
hi! I have a struct such as this one:
public readonly struct InternerId
{
private readonly int _id;

internal InternerId(int id)
{
_id = id;
}
}
public readonly struct InternerId
{
private readonly int _id;

internal InternerId(int id)
{
_id = id;
}
}
What's the correct way to implement equality between two InternerIds based on _id? I don't want equality with any other type except itself.
38 replies
CC#
Created by __dil__ on 10/8/2023 in #help
✅ I don't understand how to test my project.
I have an existing command line project. Since this is a pretty complex project with multiple complex parts, I want to ensure everything is working correctly. How do I go about adding xUnit to this project?
58 replies
CC#
Created by __dil__ on 10/7/2023 in #help
✅ Introduce variable in `while` condition
Is it possible to achieve something like this? (pseudo-C#)
while (Computation() val when val != otherVal)
// You can use `val` here...
while (Computation() val when val != otherVal)
// You can use `val` here...
The idea is that the loop should go until the result of some computation does not match some predicate, and to also keep the result of the computation around in the loop. If not, how would you achieve a similar pattern?
9 replies
CC#
Created by __dil__ on 10/7/2023 in #help
✅ How to pattern-match a `Rune`?
is this the best I can do?
myRune switch
{
_ when myRune == (Rune)'A' => 3,
_ when myRune == (Rune)'B' => 4,
// ...
}
myRune switch
{
_ when myRune == (Rune)'A' => 3,
_ when myRune == (Rune)'B' => 4,
// ...
}
That's very noisy visually and it's unclear to me if the compiler is smart enough to perform the (Rune) cast on char literals at compile-time. Is there not a way to specify a constant/literal Rune value?
41 replies
CC#
Created by __dil__ on 10/7/2023 in #help
❔ char utf16-length
since utf16 is variable-width, given a char, how can I tell how many bytes it requires when encoded in utf16?
55 replies
CC#
Created by __dil__ on 10/6/2023 in #help
❔ Generics and nullable types
This snippet below results in an error
class Foo<T>
{
T? _foo;

Foo()
{
_foo = null; // Error here
}
}
class Foo<T>
{
T? _foo;

Foo()
{
_foo = null; // Error here
}
}
Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
I don't really understand the error. I thought the type of _foo was T?, not T.
58 replies
CC#
Created by __dil__ on 10/6/2023 in #help
❔ Disable specific formatting rule only in one class in Rider
So, I have a class that is a bit pathological in that it has a bunch of one-liner declarations. Rider puts an extra newline between them which takes a ton of space and actually makes it harder to read. I found that there's a setting for this "blank lines in declarations", but I only want this in this specific class, not anywhere else. Is it possible?
5 replies
CC#
Created by __dil__ on 10/6/2023 in #help
❔ Enum with data
I'm working on a lexer, and I'm encountering this problem where I need to associate different data with different token types. My first attempt was this:
internal enum TokenKind
{
A,
B,
C
}

internal struct Token
{
private TokenKind kind;

// Optional properties depending on which token kind
internal long? AData { get; }
internal string? BData { get; }
internal bool? CData { get; }
}
internal enum TokenKind
{
A,
B,
C
}

internal struct Token
{
private TokenKind kind;

// Optional properties depending on which token kind
internal long? AData { get; }
internal string? BData { get; }
internal bool? CData { get; }
}
then you can use it like so:
switch (token.kind)
{
case TokenKind.A:
// Do something with AData
Console.WriteLine(token.AData!);
break;
case TokenKind.B:
// Do something with BData
Console.WriteLine(token.BData!);
break;
case TokenKind.C:
// Do something with CData
Console.WriteLine(token.CData!);
break;
}
switch (token.kind)
{
case TokenKind.A:
// Do something with AData
Console.WriteLine(token.AData!);
break;
case TokenKind.B:
// Do something with BData
Console.WriteLine(token.BData!);
break;
case TokenKind.C:
// Do something with CData
Console.WriteLine(token.CData!);
break;
}
I kind of dislike this implementation though. For one it seems kind of messy with the null-forgiving stuff, but it also makes the token type very bulky since it requires a separate field for every data variant. Since there will be a ton of tokens, it's important to minimize their size. It's also error-prone in the sense that someone can try to read data without first checking the token kind. What I'm trying to do is conceptually this:
enum TokenKind {
A(i64),
B(String),
C(bool),
}
enum TokenKind {
A(i64),
B(String),
C(bool),
}
It doesn't have to look like this, but this is the kind of behavior I'm looking for (Rust enums, or algebraic sum types for those who know). What would be the clean way to make this in C#? Bear in mind There is actually a lot of token kinds, and not all token kinds have data associated with them (in fact the majority do not).
76 replies
CC#
Created by __dil__ on 10/5/2023 in #help
❔ Reading from stdin
So, I'm trying to work with basic IO stuff. I have this snippet:
string line;
while ((line = Console.ReadLine()) != null) {
// Stuff...
}
string line;
while ((line = Console.ReadLine()) != null) {
// Stuff...
}
I get a warning about assigning a nullable value to a non-nullable variable. I understand what the warning is saying, but I'm not sure how I'm supposed to do any better than this considering I am already checking for null values. Any recommendations?
8 replies
CC#
Created by __dil__ on 10/5/2023 in #help
❔ How to structure project and import items?
I'm just starting with C#, and I'm having trouble understanding how project structure and importing works. I come from Rust where you can import a single item from a module with something like
use the_module::TheItem;
use the_module::TheItem;
You can also import multiple items using this notation:
use the_module::{Item1, item_2};
use the_module::{Item1, item_2};
I tried something similar in C#:
using my_namespace.TestClass;
using my_namespace.TestClass;
But that gives an error Namespace name expected .... Is it not possible to only import some items from a namespace? I'm also having trouble understanding the relationship between namespaces and files. It seems like you can add stuff to a namespace from anywhere inside your project. So it seems like namespaces are not really self-contained modules, but more like heaps where you can throw in anything semi-related to some concept. Finally it seems to me like you can't have items private to a module? This all seems rather unstructured to me, so surely I must be missing something. I can summarize my questions as such: 1. Can you import only specific items? 2. What's the idiomatic way to structure complex libraries? namespace per file? 3. What are the tools to restrict visibility such that I can have parts of my library that are only available internally? Please bear in mind I'm not familiar with "old-school" OOP stuff so I might be oblivious to the obvious 🙂 I would highly appreciate it if you could explain how it works.
62 replies
CC#
Created by __dil__ on 9/18/2023 in #help
❔ Entry API for dictionaries?
Rust has this nifty API called Entry which allows one to write code such as:
map.entry(c)
.and_modify(|count_of_c| { *count_of_c += 1 })
.or_insert(1);
map.entry(c)
.and_modify(|count_of_c| { *count_of_c += 1 })
.or_insert(1);
So, you can modify a value in a hashmap (dictionary) if the key exists, or insert a new entry if the key does not exist. Is there something similar in C#?
26 replies
CC#
Created by __dil__ on 9/18/2023 in #help
❔ Is there a built-in way to map (transform) a tuple?
For example, I'd like to do this (hypothetical code):
bool foo = (val: 1.0, truthiness: true, name: "hello").Map((bar) => { bar.val > 0 && bar.name == "Bob" || bar.truthiness });
bool foo = (val: 1.0, truthiness: true, name: "hello").Map((bar) => { bar.val > 0 && bar.name == "Bob" || bar.truthiness });
instead of that
var bar = (val: 1.0, truthiness: true, name: "hello");
bool foo = bar.val > 0 && bar.name == "Bob" || bar.truthiness;
var bar = (val: 1.0, truthiness: true, name: "hello");
bool foo = bar.val > 0 && bar.name == "Bob" || bar.truthiness;
The reasoning is that it's cumbersome to have to introduce variable names for intermediate computations involving tuples. Being able to transform them directly makes it possible to avoid that.
9 replies
CC#
Created by __dil__ on 9/17/2023 in #help
✅ Switch pattern matching with integers
Is this a valid/idiomatic way to use pattern matching to compare integers?
public static double SuccessRate(int speed) =>
speed switch
{
0 => 0.0,
< 5 => 1.0,
< 9 => 0.9,
9 => 0.8,
10 => 0.77,
_ => throw new Exception($"Expected speed between 0 and 10, got `{speed}`")
};
public static double SuccessRate(int speed) =>
speed switch
{
0 => 0.0,
< 5 => 1.0,
< 9 => 0.9,
9 => 0.8,
10 => 0.77,
_ => throw new Exception($"Expected speed between 0 and 10, got `{speed}`")
};
One thing bugging me in particular is: are the arms checked in the order they were written, or is the order not guaranteed? If the order is not guaranteed, then obviously the code above does not work.
45 replies
CC#
Created by __dil__ on 9/17/2023 in #help
❔ Iterate over a range
What's the equivalent of this (rust)
for i in 0..10 { /* ...do stuff... */ }
for i in 0..10 { /* ...do stuff... */ }
in C#? So basically, how to loop over a range? I'm not a big fan of C-style loops 😄 I find them very noisy and cumbersome.
28 replies