Jason_Bjorn
Jason_Bjorn
CC#
Created by Jason_Bjorn on 8/23/2024 in #help
✅ Avalonia - Can't see anything even though control is styled
No description
3 replies
CC#
Created by Jason_Bjorn on 8/16/2024 in #help
Avalonia IconPath not showing up
No description
9 replies
CC#
Created by Jason_Bjorn on 8/12/2024 in #help
✅ Avalonia - Textbox text changed
How can I react if the text in a TextBox https://reference.avaloniaui.net/api/Avalonia.Controls/TextBox/ changes. Right now I am using KeyUp but that doesn't handle things like backspace
2 replies
CC#
Created by Jason_Bjorn on 8/9/2024 in #help
✅ A nicer way to create an on-demand property?
Is there a nicer way to create sum here?
Foo f = new() {
X = 3,
Y = 4
};

f.Dump();

class Foo
{
public required int X { get; init; }
public required int Y { get; init; }
private int? sum = null;

public int Sum
{
get
{
Console.WriteLine("Calculating Sum");
sum ??= X + Y;
return sum.Value;
}
}
}
Foo f = new() {
X = 3,
Y = 4
};

f.Dump();

class Foo
{
public required int X { get; init; }
public required int Y { get; init; }
private int? sum = null;

public int Sum
{
get
{
Console.WriteLine("Calculating Sum");
sum ??= X + Y;
return sum.Value;
}
}
}
14 replies
CC#
Created by Jason_Bjorn on 8/9/2024 in #help
✅ Generic function with conditional type based logic inside
How can I make something like this work? I want the user to either be able to get a list of ints or strings.
List<int> lInt = Foo<int>();
List<string> lString = Foo<string>();

// Should either returns a List of Ints or strings
List<T> Foo<T>()
{
List<T> list = new();

for (int i = 0; i < 10; i++)
{
T valueToAdd;
if (typeof(T) == typeof(int))
{
valueToAdd = i;
}
else if (typeof(T) == typeof(string))
{
valueToAdd = i.ToString();
}
else {
throw new InvalidOperationException($"Invalid type {typeof(T)}");
}
list.Add(valueToAdd);
}
return list;
}
List<int> lInt = Foo<int>();
List<string> lString = Foo<string>();

// Should either returns a List of Ints or strings
List<T> Foo<T>()
{
List<T> list = new();

for (int i = 0; i < 10; i++)
{
T valueToAdd;
if (typeof(T) == typeof(int))
{
valueToAdd = i;
}
else if (typeof(T) == typeof(string))
{
valueToAdd = i.ToString();
}
else {
throw new InvalidOperationException($"Invalid type {typeof(T)}");
}
list.Add(valueToAdd);
}
return list;
}
31 replies
CC#
Created by Jason_Bjorn on 8/8/2024 in #help
✅ Benchmarks not running
No description
2 replies
CC#
Created by Jason_Bjorn on 8/1/2024 in #help
✅ Custom `IComparer` adds so much overhead
Is there a way I can avoid having to make a whole new class for the IComparer interface here? https://dotnetfiddle.net/yRh9YN
using System.Collections.Generic;
using System;
#nullable enable

SortedList<string, int> l = new(new RomanNumeralComparer())
{
// shuffled on purpose
{ "V", 5 },
{ "I", 1 },
{ "L", 50 },
{ "X", 10 },
};


// correctly prints in the order of
// I V X L
foreach (var c in l)
{
Console.WriteLine(c);
}

// big class for something so small
public class RomanNumeralComparer : IComparer<string>
{
private readonly string _order = "IVXL";

public int Compare(string? x, string? y)
{
if (x is null && y is null)
{
return 0;
}

if (x is null)
{
return -1;
}

if (y is null)
{
return 1;
}

int xRank = _order.IndexOf(x, StringComparison.InvariantCulture);
int yRank = _order.IndexOf(y, StringComparison.InvariantCulture);

return (xRank < yRank) ? -1 : (xRank == yRank) ? 0 : 1;
}
}
using System.Collections.Generic;
using System;
#nullable enable

SortedList<string, int> l = new(new RomanNumeralComparer())
{
// shuffled on purpose
{ "V", 5 },
{ "I", 1 },
{ "L", 50 },
{ "X", 10 },
};


// correctly prints in the order of
// I V X L
foreach (var c in l)
{
Console.WriteLine(c);
}

// big class for something so small
public class RomanNumeralComparer : IComparer<string>
{
private readonly string _order = "IVXL";

public int Compare(string? x, string? y)
{
if (x is null && y is null)
{
return 0;
}

if (x is null)
{
return -1;
}

if (y is null)
{
return 1;
}

int xRank = _order.IndexOf(x, StringComparison.InvariantCulture);
int yRank = _order.IndexOf(y, StringComparison.InvariantCulture);

return (xRank < yRank) ? -1 : (xRank == yRank) ? 0 : 1;
}
}
32 replies
CC#
Created by Jason_Bjorn on 7/22/2024 in #help
✅ Improving code
I have this old method and then I didn't like how repetative the logic was so I put it in a lambda. I was wondering is there a better/more c# idomatic way still?
// old method
temp changed by more than 10%
if (Math.Abs(e.NewTemperature - e.OldTemperature) > 0.10)
{
Console.WriteLine("Temperature changed by more than 10%");
}

if (Math.Abs(e.NewHumidity - e.OldTemperature) > 0.10)
{
Console.WriteLine("Humidity changed by more than 10%");
}

// new method
// lambda, static to not capture anything
static bool isWithinPercentage(double value1, double value2, double decimalPercentage) => (Math.Abs(value1 - value2) <= decimalPercentage);
if (!isWithinPercentage(e.NewTemperature, e.OldTemperature, 0.10))
{
Console.WriteLine("Temperature changed by more than 10%");
}

if (!isWithinPercentage(e.NewHumidity, e.OldHumidity, 0.10))
{
Console.WriteLine("Humidity changed by more than 10%");

}
// old method
temp changed by more than 10%
if (Math.Abs(e.NewTemperature - e.OldTemperature) > 0.10)
{
Console.WriteLine("Temperature changed by more than 10%");
}

if (Math.Abs(e.NewHumidity - e.OldTemperature) > 0.10)
{
Console.WriteLine("Humidity changed by more than 10%");
}

// new method
// lambda, static to not capture anything
static bool isWithinPercentage(double value1, double value2, double decimalPercentage) => (Math.Abs(value1 - value2) <= decimalPercentage);
if (!isWithinPercentage(e.NewTemperature, e.OldTemperature, 0.10))
{
Console.WriteLine("Temperature changed by more than 10%");
}

if (!isWithinPercentage(e.NewHumidity, e.OldHumidity, 0.10))
{
Console.WriteLine("Humidity changed by more than 10%");

}
3 replies
CC#
Created by Jason_Bjorn on 7/17/2024 in #help
✅ IL for function vs expression-bodied-function
Why do these two compile to different things?
class Program {
int Double1(int n) => n + n;

int Double2(int n) {
return n + n;
}
}
class Program {
int Double1(int n) => n + n;

int Double2(int n) {
return n + n;
}
}
14 replies
CC#
Created by Jason_Bjorn on 7/14/2024 in #help
✅ Double-Async
Is Method1 double async here?
public static async Task<string> Method1()
{
var client = new HttpClient();
Console.WriteLine("in ");
var content = await client.GetStringAsync("https://microsoft.com");
return content;
}

public static Task<string> Method2()
{
var client = new HttpClient();
return client.GetStringAsync("https://microsoft.com");
}
public static async Task<string> Method1()
{
var client = new HttpClient();
Console.WriteLine("in ");
var content = await client.GetStringAsync("https://microsoft.com");
return content;
}

public static Task<string> Method2()
{
var client = new HttpClient();
return client.GetStringAsync("https://microsoft.com");
}
46 replies
CC#
Created by Jason_Bjorn on 7/13/2024 in #help
✅ [AllowedValue] not doing anything
Why is my code allowing the name "Jimmy" ?
using System.ComponentModel.DataAnnotations;

public class Foo
{
[AllowedValues(new object [] {"Bill", "Bob"}, "Entered illegal name")]
public string Name { get; set; }
}

class Program
{
public static void Main()
{
Foo f = new()
{
Name = "Jimmy" // works ???
};
}
}
using System.ComponentModel.DataAnnotations;

public class Foo
{
[AllowedValues(new object [] {"Bill", "Bob"}, "Entered illegal name")]
public string Name { get; set; }
}

class Program
{
public static void Main()
{
Foo f = new()
{
Name = "Jimmy" // works ???
};
}
}
19 replies
CC#
Created by Jason_Bjorn on 7/8/2024 in #help
✅ LINQ, simple query
Is there something I can do to make this query better (faster, more idiomatic, etc)
public record Course(
string Title,
string Category,
int Number,
DateOnly PublicationDate,
TimeSpan Duration)
{
public static readonly Course[] Catalog =
[
new Course(
Title: "Elements of Geometry",
Category: "MAT", Number: 101, Duration: TimeSpan.FromHours(3),
PublicationDate: new DateOnly(2009, 5, 20)),
new Course(
Title: "Squaring the Circle",
Category: "MAT", Number: 102, Duration: TimeSpan.FromHours(7),
PublicationDate: new DateOnly(2009, 4, 1)),
new Course(
Title: "Recreational Organ Transplantation",
Category: "BIO", Number: 305, Duration: TimeSpan.FromHours(4),
PublicationDate: new DateOnly(2002, 7, 19)),
new Course(
Title: "Hyperbolic Geometry",
Category: "MAT", Number: 207, Duration: TimeSpan.FromHours(5),
PublicationDate: new DateOnly(2007, 10, 5)),
new Course(
Title: "Oversimplified Data Structures for Demos",
Category: "CSE", Number: 104, Duration: TimeSpan.FromHours(2),
PublicationDate: new DateOnly(2023, 11, 8)),
new Course(
Title: "Introduction to Human Anatomy and Physiology",
Category: "BIO", Number: 201, Duration: TimeSpan.FromHours(12),
PublicationDate: new DateOnly(2001, 4, 11)),
];
}

class Program
{
public static void Main()
{

// all the courses that are 4hrs or longer grouped by their category. What is shown: Title, Course-Number, duration
var q = Course.Catalog.Where(course => course.Duration.TotalHours >= 4).GroupBy(course => course.Category, course => new { course.Title, course.Number, course.Duration.TotalHours });
q.Dump();
}
}
public record Course(
string Title,
string Category,
int Number,
DateOnly PublicationDate,
TimeSpan Duration)
{
public static readonly Course[] Catalog =
[
new Course(
Title: "Elements of Geometry",
Category: "MAT", Number: 101, Duration: TimeSpan.FromHours(3),
PublicationDate: new DateOnly(2009, 5, 20)),
new Course(
Title: "Squaring the Circle",
Category: "MAT", Number: 102, Duration: TimeSpan.FromHours(7),
PublicationDate: new DateOnly(2009, 4, 1)),
new Course(
Title: "Recreational Organ Transplantation",
Category: "BIO", Number: 305, Duration: TimeSpan.FromHours(4),
PublicationDate: new DateOnly(2002, 7, 19)),
new Course(
Title: "Hyperbolic Geometry",
Category: "MAT", Number: 207, Duration: TimeSpan.FromHours(5),
PublicationDate: new DateOnly(2007, 10, 5)),
new Course(
Title: "Oversimplified Data Structures for Demos",
Category: "CSE", Number: 104, Duration: TimeSpan.FromHours(2),
PublicationDate: new DateOnly(2023, 11, 8)),
new Course(
Title: "Introduction to Human Anatomy and Physiology",
Category: "BIO", Number: 201, Duration: TimeSpan.FromHours(12),
PublicationDate: new DateOnly(2001, 4, 11)),
];
}

class Program
{
public static void Main()
{

// all the courses that are 4hrs or longer grouped by their category. What is shown: Title, Course-Number, duration
var q = Course.Catalog.Where(course => course.Duration.TotalHours >= 4).GroupBy(course => course.Category, course => new { course.Title, course.Number, course.Duration.TotalHours });
q.Dump();
}
}
19 replies
CC#
Created by Jason_Bjorn on 7/3/2024 in #help
✅ Why is the attempted fix still creating a new copy of the dv each time CallDispose is called?
// given, results in "Disposing for first time" being printed 3 times
// static void CallDispose(IDisposable o)
// {
// o.Dispose();
// }

// attempted fix, still prints "Disposing for first time" 3 times
static void CallDispose<T>(T o) where T : IDisposable
{
o.Dispose();
}

DisposableValue dv = new();
Console.WriteLine("Passing value variable:");
CallDispose(dv);
CallDispose(dv);
CallDispose(dv);

public struct DisposableValue : IDisposable
{
private bool _disposedYet;

public void Dispose()
{
if (!_disposedYet)
{
Console.WriteLine("Disposing for first time");
_disposedYet = true;
}
else
{
Console.WriteLine("Was already disposed");
}
}
}
// given, results in "Disposing for first time" being printed 3 times
// static void CallDispose(IDisposable o)
// {
// o.Dispose();
// }

// attempted fix, still prints "Disposing for first time" 3 times
static void CallDispose<T>(T o) where T : IDisposable
{
o.Dispose();
}

DisposableValue dv = new();
Console.WriteLine("Passing value variable:");
CallDispose(dv);
CallDispose(dv);
CallDispose(dv);

public struct DisposableValue : IDisposable
{
private bool _disposedYet;

public void Dispose()
{
if (!_disposedYet)
{
Console.WriteLine("Disposing for first time");
_disposedYet = true;
}
else
{
Console.WriteLine("Was already disposed");
}
}
}
19 replies
CC#
Created by Jason_Bjorn on 7/1/2024 in #help
✅ Two methods: struct and non-struct
Why does b.F(42) call the 2nd overload? 42 is a value-type which is what structs are?
public class Base
{
public virtual void F<T>(T? t) where T : struct { }
public virtual void F<T>(T? t) { }
}

Base b = new();
int? nullInt = null;
int? nonNullNullableInt = 42;

// These call the 1st overload.
b.F(nullInt);
b.F(nonNullNullableInt);
b.F(default(int?));

// These call the 2nd overload.
b.F(42);
b.F("Hello");
b.F(default(int));
public class Base
{
public virtual void F<T>(T? t) where T : struct { }
public virtual void F<T>(T? t) { }
}

Base b = new();
int? nullInt = null;
int? nonNullNullableInt = 42;

// These call the 1st overload.
b.F(nullInt);
b.F(nonNullNullableInt);
b.F(default(int?));

// These call the 2nd overload.
b.F(42);
b.F("Hello");
b.F(default(int));
9 replies
CC#
Created by Jason_Bjorn on 6/29/2024 in #help
Why `where T: class`
No description
8 replies
CC#
Created by Jason_Bjorn on 6/27/2024 in #help
LINQ help
I have a collection of ints, how can I take the last three that are bigger than 100? is there a better way than this?
using System;
using System.Linq;

class Program
{
static void Main()
{
int[] numbers = { 80, 120, 110, 90, 10, 140, 150, 50, 22, -800 };

var result = numbers.Where(num => num > 100).Reverse().Take(3).Reverse().ToArray();

Console.WriteLine("Last 3 elements over 100:");
foreach (var num in result)
{
Console.WriteLine(num);
}
}
}
using System;
using System.Linq;

class Program
{
static void Main()
{
int[] numbers = { 80, 120, 110, 90, 10, 140, 150, 50, 22, -800 };

var result = numbers.Where(num => num > 100).Reverse().Take(3).Reverse().ToArray();

Console.WriteLine("Last 3 elements over 100:");
foreach (var num in result)
{
Console.WriteLine(num);
}
}
}
26 replies