InBetween

1

votes
1

answer
100

views

Why can't I inherit from a private class / interface?

Why is this illegal in C#? class Foo: Foo.BaseFoo //Circular base class dependency compile time error { private class BaseFoo {...} ... } I'm not arguing when this could be useful or not, but I'd like to know what are the reasons that would disallow such code to compile. A similar restriction happen...
InBetween
1

votes
1

answer
71

views

Weird performance test behavior

As a follow up of the question I posted yesterday, Mathematics and generics I decided to go ahead and put together a simple RealNumber class wrapping decimal to enable generic mathematics and do some simple tests to see performance compared (please do not comment on why, what for or how to implement...
InBetween
1

votes
2

answer
183

views

How to know a value overflows without recurring to a runtime OverflowException

So the question is: Given a native integral type that represents the largest possible number in a given compiler (language?), for example ulong in C#, how do you detect that an input string representing a number is going to overflow the largest value that is representable by that given type without...
InBetween
1

votes
2

answer
50

views

Wrong compiler warning when overriding interface implementation?

Consider the following code: interface IFooable { void Foo(); } class Blah : IFooable { public void Foo() { Console.WriteLine('Hi from 'Blah''); } } class Bar : Blah, IFooable { public void Foo() { Console.WriteLine('Hi from 'Bar''); } } Compiling this code will give the following warning in the com...
InBetween
18

votes
2

answer
930

views

False C# compiler warning?

Ok, this is a far stretched corner case we stumbled upon, but it made me curious. Consider the following code: public class Foo { private int foo; public int Reset() => foo = 0; //remember, assignment expressions //return something! } Will this code compile? No, it won't if you have fail on all war...
InBetween
5

votes
4

answer
2.1k

views

How to use scientific notation in const fields?

I'm working in a math library, and due to the inherent troubles of working with double I am coding all equality comparisons type a == b as Math.Abs(a - b)
InBetween
4

votes
3

answer
212

views

Why does this checked calculation not throw OverflowException?

Can somebody please explain the following behavior: static void Main(string[] args) { checked { double d = -1d + long.MinValue; //this resolves at runtime to -9223372036854780000.00 //long obviousOverflow = -9223372036854780000; //compile time error, '-' cannot be applied to operand of tpye ulong ->...
InBetween
2

votes
4

answer
137

views

Ifs, else ifs and multiple returns [closed]

This is not a question about chained ifs or ifs and else ifs. I've seen quite a few of those questions posted in SO already. My question is also not about performance, its more about coding standards and readability. Consider the following trivial pseudocode I'm seeing a lot in a project I'm working...
InBetween
3

votes
4

answer
147

views

Interface and class inheritance. Is this an avoidable pattern?

I'd appreciate any advice on which way to go on in the following scenario. Let's see if I can explain it clearly (english is not my native language so things might get confusing, sorry). Suppose I have the following interfaces: internal interface IBlah { int Frob(); } internal interface IBlahOnStero...
InBetween
6

votes
1

answer
102

views

Is twice implementing an explicit interface to achieve “virtual” behavior an ugly hack?

Ok, this arises from some discussion going on here. Imagine the following scenario. Company Alpha publishes library Charlie which exposes among others, a type Charlie.Bar that explicilty implements the interface IFooable: public interface IFooable { void Foo(); } namespace Charlie { public clas Bar:...
InBetween
6

votes
4

answer
574

views

Compile time constants and reference types

Ok, consider the following code: const bool trueOrFalse = false; const object constObject = null; void Foo() { if (trueOrFalse) { int hash = constObject.GetHashCode(); } if (constObject != null) { int hash = constObject.GetHashCode(); } } trueOrFalse is a compile time constant and as such, the compi...
InBetween
4

votes
5

answer
257

views

Why is enum casting allowed even when there is no valid value defined in the enumeration

When reading Jon Skeet's answer to this particular question How can I make it so my class variables can only be set to one of three choices? y learned something new I was not aware of in C# and I guess the CLR type system. What is the reasoning behind this being legal: public enum Tests { Zero = 0,...
InBetween
6

votes
3

answer
935

views

Confused about operator overloading

As I progress on my little math library I'm stumbling upon certain aspects of C# and the .NET Framework that I'm having some trouble understanding. This time it's operator overloading and specifically the term overloading itself. Why is it called overloading? Do all objects by default have an implem...
InBetween
2

votes
1

answer
64

views

Why does the compiler not infer the generic type

I have the following method: public static void Foo(Predicate validator) { ... } And I want to call it the following way: Foo(s => string.IsNullOrEmpty(s)); Why can't the compiler figure out s is string and therefore T is string? What rule in the spec makes the inference algorithm fail here?
InBetween
6

votes
3

answer
83

views

Can exceptions used as a control flow mechanism be valid in some specific scenarios?

I'm tweaking some code in a RationalNumber implementation. In particular, inside the equality logic, I'm considering the following: public bool Equals(RationalNumber other) { if (RationalNumber.IsInfinity(this) || RationalNumber.IsInfinity(other) || RationalNumber.IsNaN(this) || RationalNumber.IsNaN...
InBetween
41

votes
4

answer
753

views

Don't understand pre decrement operator behavior with Nullable type

Ok, this might be obvious for some of you but I am stumped with the behavior I'm getting from this rather simple code: public static void Main(string[] args) { int? n = 1; int i = 1; n = ++n - --i; Console.WriteLine('Without Nullable n = {0}', n); //outputs n = 2 n = 1; i = 1; n = ++n - new Nullable...
InBetween
43

votes
5

answer
1.9k

views

Can an immutable type change its internal state?

The question is simple. Can a type that can change its internal state without it being observable from the outside be considered immutable? Simplified example: public struct Matrix { bool determinantEvaluated; double determinant; public double Determinant { get //asume thread-safe correctness in im...
InBetween
6

votes
1

answer
108

views

String interning. How does the compiler know?

I know what string interning is, and why the following code behaves the way it does: var hello = 'Hello'; var he_llo = 'He' + 'llo'; var b = ReferenceEquals(hello, he_llo); //true Or var hello = 'Hello'; var h_e_l_l_o = new string(new char[] { 'H', 'e', 'l', 'l', 'o' }); var b = ReferenceEquals(hell...
InBetween
5

votes
0

answer
164

views

New C#7 pattern matching and reachability

This is based on this question, which seems to me a language glitch or a missing warning in the compiler. My reasoning is that is will always return true in expressions of the following type: int i; if (i is var j) .... Taking it a step further, consider the following code: int i; if (i is int) .......
InBetween
5

votes
2

answer
106

views

Algorithm for testing inequality of ordered large collections

Ok, I need to test if two IEnumerable are equal. The order of the elements is important, which means that: {1, 2, 4, 1, 3} and {1, 2, 1, 3, 4} should not be equal. I've seen a few answers on this site explaining how to do this with linq: for example, here The problem is that I have to repeatedly tes...
InBetween
2

votes
1

answer
66

views

Boundary between Lexer and Parser

I'm working on a pet project and I have to implement a lexer/parser. I'm reading about the subject and prototyping a simple math parser to understand as I go along. There is something I still don't understand quite right, and it's the boundary between the lexer and the parser. Consider the following...
InBetween
6

votes
1

answer
383

views

Confused with little used Value Type initialization

The following code is illegal: public struct MyStruct { public MyStruct(int a, int b) { this.a = a; this.b = b; } public int a; public int b; } //now I want to cache for whatever reason the default value of MyStruct MyStruct defaultValue; ... if (foo != defaultValue) //use of unassigned variable......
InBetween
8

votes
4

answer
242

views

Field initializer accesing 'this' reloaded

This question is an extension of Cristi Diaconescu's about the illegality of field initializers accesing this in C#. This is illegal in C#: class C { int i = 5; double[] dd = new double[i]; //Compiler error: A field initializer cannot reference the non-static field, method, or property. } Ok, so the...
InBetween
3

votes
1

answer
117

views

About operator overload resolution

Suppose two classes with the following implicit and explicit operator pattern: class Foo { public static implicit operator decimal (Foo foo) { throw new NotImplementedException(); } public static implicit operator Foo (decimal value) { throw new NotImplementedException(); } public static Foo operato...
InBetween
4

votes
1

answer
473

views

Getting the callee's name of an extension method

I've built up a simple ArgumentValidator class in order to simplify argument preconditions in any given method. Most of them are null or bounds checks and it gets pretty tedious after a couple of if (arg == null ) throw new ArgumentNullException(nameof(arg)); So I've come up with the following set u...
InBetween
8

votes
1

answer
505

views

Commutativity in operators

In C#, there is not in-built notion of commutativity in the language. That is if I define a simple Vector class for instance: public struct Vector { private readonly double x, y, z; ... public static Vector operator +(Vector v, double d) {...} } I will still need to define the symmetric operator +(d...
InBetween
8

votes
2

answer
490

views

Subtracting uint and int and constant folding

Based on this interesting question: Addition of int and uint and toying around with constant folding as mentioned in Nicholas Carey's answer, I've stumbled upon a seemingly inconsistent behavior of the compiler: Consider the following code snippet: int i = 1; uint j = 2; var k = i - j; Here the comp...
InBetween
6

votes
1

answer
1k

views

dynamic field const vs. any old reference field const behavior

This probably has a simple explanation I'm failing to see, but why is the following code legal: public struct Foo { const object nullObject = null; public override string ToString() { if (nullObject == null) { return base.ToString(); } } } While the following, public struct Foo { const dynamic nullO...
InBetween
6

votes
3

answer
468

views

Microsoft.VisualStudio.TestTools.UnitTesting.Assert generic method overloads behavior

In the Microsoft.VisualStudio.TestTools.UnitTesting namespace, there is the handy static class Assert to handle the assertions going on in your tests. Something that has got me bugged is that most methods are extremely overloaded, and on top of that, they have a generic version. One specific example...
InBetween
4

votes
3

answer
246

views

Can you use nameof when hidden by in scope member?

Consider the following legacy code: public class Foo { public void Blah(string frob) { if (frob == null) throw new ArgumentException('frob'); } public string nameof() { //boring code } } Now imagine part of this code is being refactored, and we want to refactor Blah in the following way: public void...
InBetween
3

votes
4

answer
1.5k

views

IDisposable and CA2000 warning during VS2010 Code Analysis

I need some advice here, I hope somebody can help me. I have the following class structure (simplified): public class Bar: IDisposable {...} public abstract class FooBase: IDisposable { Bar bar; bool disposed; internal FooBase(Bar bar) { this.bar=bar; } public void Dispose() { Dispose(true); GC.Supr...
InBetween
15

votes
1

answer
277

views

Is a pure type the same as an immutable type?

I was checking out the documentation of PureAttribute in MSDN and I was surprised that it can be applied at class level. I knew what a pure function is, but I had never seen it applied to a type. In the MSDN documentation it states the following: Indicates that a type or method is pure, that is, it...
InBetween
2

votes
1

answer
77

views

Is there a way to get the declaring method/property of an Attribute at runtime [duplicate]

This question already has an answer here: How do I get the member to which my custom attribute was applied? 4 answers Ok, consider the following scenario: public class Foo() { [FooProperty] public int Blah { get { .... } } ... } [AttributeUsage(AttributeTargets.Property)] public class FooPropertyAt...
InBetween
2

votes
1

answer
75

views

How to detect a potential overflow

OK, consider the following scenario: public static bool TryGetNearestRationalNumber(double target, double precision, out RationalNumber nearest) { //implements continued fractions to solve the problem. Only relevant code is shown. var integerPart = (long)target; //necessary for algorithm var fractio...
InBetween
5

votes
3

answer
104

views

Evaluate in property getter or when creating an instance?

Ok, an easy question. First of all, I have to say that my concern is not performance. I'm totally aware that whatever performance costs one option or the other may entail are probably meaningless and not even worth considering in normal scenarios. It has more to do with design standards and curiosit...
InBetween
3

votes
0

answer
153

views

Overloading with 'different' return type

I have always read that overloaded methods should always return the same type whenever possible. However I've come upon a scenario which I really don't know if it could be considered as having different return types or not. Consider the following implementation to obtain the permutations of all elem...
InBetween
6

votes
2

answer
1k

views

Loading an Assembly if a certain Attribute is present

Ok, here is the deal: I want to load a user defined Assembly into my AppDomain, but I only want to do so if the specified Assembly matches some requirements. In my case, it must have, among other requirements, an Assembly level Attribute we could call MandatoryAssemblyAttribute. There are two paths...
InBetween
3

votes
2

answer
93

views

Should I throw an exception if using an invalid generic type and if yes, which one?

I am building a simple custom lightweight csv generator class named, oddly enough, CsvWriter. The way this class works is that it will automatically generate a csv to an underlying Stream from all public properties that are marked with a predefined attribute that we aptly named CsvPropertyAttribute....
InBetween
8

votes
3

answer
205

views

Using block galore?

I'd like your opinion on the following subject: Imagine we have a method that is responsible of achieving one specific purpose, but to do so, it needs the support of an important number of locally scoped objects, many of them implementing IDisposable. MS coding standards say that when using local ID...
InBetween
3

votes
3

answer
139

views

CPUs not like humans? 0 + 0 not easier than 10E12 + 9E15?

My kid asked me a funny question yesterday: Dad, does a computer have trouble adding / multiplying large numbers like I do? Does it take longer? I laughed and answered of course not, computers are equally fast with any numbers, they are that smart. Later, I started thinking about it and asked myself...
InBetween

View additional