Why not allow Extension method definition in nested class? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I would find it convenient/logical to write my exensions for a class in a nested class. The main reason is I could simply name that class Extensions and let it's outer naming scope give it a unique type name for the compiler.
What is the technical reason to disallow something like:
public class Foo
{
ObjectSet<Bar> Bars { get; set; }
public static class Extensions
{
public static Bar ByName(this ObjectSet<Bar> bars, string name)
{
return bars.FirstOrDefault(c => c.Name == name);
}
}
}
Whereas now I have to create a separate free standing class.
Update/Note: I wasn't imagining that the fact it was an inner class would affect the scope of availability of the extension method. I only wanted to address the practical coding issue a separate class with a separate name.

The key point here is that nested classes can access private fields in the outer class.
So the following code works:
public class Foo
{
private bool _field;
public static class Extensions
{
public static bool GetField(Foo foo)
{
return foo._field;
}
}
}
Here you are explicitly passing in an instance of the class, and a static method is allowed to access a private field... seems reasonable:
bool fieldValue = Foo.Extensions.GetField(new Foo());
However, although extension methods are just an alternative syntax for static methods, they are invoked the same way as non-static instance methods.
Now if extension methods were allowed in nested classes, they could in fact access private fields, and they would be that much closer to instance methods. This could lead to some unintended consequences.
In summary, if this were allowed:
public class Foo
{
private bool _field;
public static class Extensions
{
public static bool GetField(*this* Foo foo) // not allowed, compile error.
{
return foo._field;
}
}
}
Then you could write the following code, making the extension method behave a bit more like an instance method than it should be:
var foo = new Foo();
var iGotAPrivateField = foo.GetField();
Edit as a result of comments
Why is it a bad idea for extension methods to be equivalent to instance methods?
In Eric Lippert's words (emphasis mine):
So, yes, the oft-heard criticism that "extension methods are not object-oriented" is entirely correct, but also rather irrelevant. Extension methods certainly are not object-oriented. They put the code that manipulates the data far away from the code that declares the data, they cannot break encapsulation and talk to the private state of the objects they appear to be methods on, they do not play well with inheritance, and so on. They're procedural programming in a convenient object-oriented dress.

There is no technical reason for it - just practical. If you have an extension method that is limited in scope to a single class, just define it as a regular static method in your class and remove the 'this'. Extensions are for sharing across several classes.

I guess the idea behind disallowing this thing is because Extension Methods are applied for all entities across the namespace.
If you will create a nested Extension Methods class then it will be applicable only to class where it is nested. In that case its not point creating an extension method. Then any normal non-extension method would do.

Related

making instance of class in c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
In this code
using System;
namespace Hello
{
class TestEmployee
{
static void Main()
{
Employee employee = new Employee();
employee.salary = 1000;
employee.bonus = 100;
employee.CacalculateTotalPay();
Console.ReadKey();
}
}
class Employee
{
public double salary;
public double bonus;
public void CacalculateTotalPay()
{
Console.WriteLine(salary + bonus);
}
}
}
Why should we make a instance of a class with the new keyword when we already declared the employee variables type with Employee class?
I didn't tried anything.
When you declare a variable for a class without the new operator any assignment, like this:
Employee employee;
you don't actually have an instance of the class yet. There is no Employee object here. What you have is a variable with the potential to refer to a class instance. Initially there isn't anything there; only the potential... it is a null reference. Therefore we might also create a new instance of the type and assign that new instance to our variable:
Employee employee = new Employee();
You could avoid this by making the Employee type static. Then, instead of declaring a variable at all you would refer to its members via the type name (ie Employee.salary). However, that's limiting. If you refer to the members via type name you would have no way to distinguish one employee from another, and you likely expect to have many more than just the one employee.
Therefore we do not use static and instead create new instances so that each instance can represent a different employee.
This can be confusing for new programmers, because the first exposure to code is often via a class with a static Main() method, where you did not need to create an instance, and with primitive types like int and string that have support in the language so you don't need to use the new operator. It may be some time before you progress far enough to need to worry about object instances. But rest assured, over time instances are the norm, and static and struct will be less common.
Finally, it is important to come to terms with the difference between object instances, references, variables, and types (classes/structs). Those are four different kinds of thing, and it is difficult to write effective code without understanding how they relate to each other.

How to initialize field in class C#/.Net in efficient and safe way? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Here is two classes MyClass and Helper, in order to have one instance of Helper class in MyClass it could be initialize with property:
public class MyClass
{
private IHelper _helper;
private IHelper Helper
{
get
{
if (_helper != null)
{
_helper = new Helper();
}
return _helper;
}
}
}
or constructor:
public class MyClass
{
private IHelper Helper { get; set; }
MyClass()
{
Helper = new Helper();
}
}
The question: What is benefits and potential issues with each solution? Is it some other better options?
The two approaches are not identical:
The first approach creates _helper on the first read; if Helper property is never accessed, no instance of Helper is created
The second approach creates _helper eagerly, meaning that you would have an instance of Helper in each instance of MyClass.
The choice between these two behaviors is based on your requirements, not on an opinion. Note that you can use Lazy<T> class to achieve the behavior from your first example with less code:
public class MyClass {
private Lazy<IHelper> _helper = new Lazy<IHelper>(() => new Helper());
private IHelper Helper {
get => _helper.Value;
}
}
Those two examples don't do the same and so there is no "matter of style", but of "how should it work". The difference is minor but still there is one:
In your first example the instance of Helper is only created if it is accessed at least once, but in your second example it is always created even if it is not needed.
Also in the second example it has a private setter an thus can be changed later on in time again.
IMO you should use the first one if it is not always used and the second one if it is needed every time, but then make the property read-only (remove the setter - setting in the constructor still works if your compiler is up to date).
Another shorter version for the first one I tend to use in such cases (Lazy<T> has some minor overhead and do not use it for "singleton like patterns"):
private IHelper helper;
public IHelper Helper => helper ?? (helper = new Helper());
NOTE: This code-example is NOT thread-safe, so if that is a requirement use the example from dasblinkenlight. Here it could happen that two instances of Helper are created if the property is accessed the same time by two threads and the second one is then set to helper in the end. If that is not the case or no problem it is safe to use. If I remember correctly the thread-safety is also the main reason why Lazy<T> creates some measurable overhead which led us to not use it in all cases.

Inheritance with static classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I don't know whether this question will make sense or if it's a naive question, but I haven't been able to find a satisfactory answer.
I would like to be able to share code across multiple static classes. Is there an "equivalent" of an abstract base class for static classes (i.e. can I have one static class inherit from another one)? If not, why not? Is there another way of sharing code across multiple static classes in a manner analogous to what you do with an abstract base class?
Also, how does a static class compare to a "sealed" class?
You're quite right. Reflection will show that a static class is both abstract and sealed:
public static class MyStaticTest {
}
...
// I'm abstract
Console.WriteLine(typeof(MyStaticTest).IsAbstract ? "I'm abstract" : "");
and that's why you can't create an instance (compile time error): new MyStaticTest();. However, reflection will show that any static class is sealed as well:
// I'm sealed
Console.WriteLine(typeof(MyStaticTest).IsSealed ? "I'm sealed" : "");
and so you can't inherit from it (compile time error): public class MyClass: MyStaticTest {..}. Thus, all you can do with static class is to declare static members (static fields, properties, methods etc.)
The abstract keyword enables to create classes and class members that are incomplete and must be implemented in a derived class whereas The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.
I think its complete for Above

C# static method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a problem with a example of my book. From what i have read non static methods cant be used without instance a object of the class. So is this ok ?
public partial class TempAgencyForm : Form
{
public TempAgencyForm()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
...
setVisibility(false);
}
private void setVisibility(bool visibilityValue)
{
...
}
}
Yes, it is fine. One non-static method can call another non-static method.
The call:
setVisibility(false);
can also be written:
this.setVisibility(false);
but the this qualifier is redundant.
However, if you had tried to call a non-static method without instance qualification from inside a static member, that would have been a problem (compile-time error).
I assume you are talking about calling setVisibility(false);. Yes it is fine, neither it or the method calling it are static.
This will all happen within an instance of TempAgencyForm
Yes this is okay, because it's called from within another member.
You're correct, since setVisibility() is not static, it always has to be called in the context of some object of the parent class (TempAgencyForm in this example).
However, btnCalculate_Click() is another member of TempAgencyForm, as such you're able to access the current/local object using the this keyword (this.setVisibility()), which is optional if there's no disambiguity.
static or non static doesnt matter here, you are calling a member function declared within the same object. so short answer is "fine"
how you call TempAgencyForm members may be what you are referring to
in this case (as you have defined) instantiations is required
TempAgencyForm taf = new TempAgencyForm()
taf.setVisibility(false);
however if you have your class definition itself as static, i.e.
public static partial class TempAgencyForm
then,
TempAgencyForm.setVisibility(false);
is suffice (without instantiating the object) as the object is already loaded on stack at the time of application start

Is it possible to define valid C# interface that cannot be implemented? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm thinking about this (meta) question for couple of days already:
Is it possible to define valid C# interface, that cannot be implemented in any way?
Possible variations of this question: Is it possible to define such interface in C# 2.0, 3.0, 4.0, 5.0? Is it possible to define such interface that would not even compile when implemented, or that would compile but throw runtime exception?
Edit: I know such interface will be useless just by definition, but is a nice answer for lectures or testing applicants for a programming job how good they know C#.
Is it possible to define valid C# interface that cannot be implemented?
This trivia question is not a good fit for StackOverflow, but what the heck, it is easily answered. (Wrongly, as it turns out! Read on!)
class C
{
private C() {}
}
interface IFoo<T> where T : C, new()
{
}
IFoo<T> cannot be implemented for any T because there is no type argument that can be substituted for T. C doesn't work because C does not have a public parameterless constructor, and there can be no derived class of C because the default constructor is private. (Well, there could be an accessible derived class of C inside C, but there isn't in this case.)
UPDATE: Commenter "mike z" correctly points out that
class X<T> : IFoo<T> where T : C, new() {}
implements the interface, though of course now there is no way to instantiate X<T>!
Even better, user "GranBurguesa" points out that a derived class of C is permitted to be declared, just so long as it never calls the private constructor; this is only possible if it crashes and dies on instantiation. (Well, to be picky, it would also be permitted for the recursive calls to be optimized down to an infinite loop instead of a crash.)
Both devious workarounds pose a philosophical question: if an interface is implemented by a class no one can instantiate, is it really implemented? Of course GranBurguesa demonstrates that IFoo<D> can be implemented and constructed, so my answer is actually wrong.
There are also cases, such as the one hinted at in SLaks' deleted answer, in which an abuse of the generic mechanism leads to an "infinitary" type. Such types are not legal in the CLR; the C# design team has considered adding similar language to the C# compiler spec but hasn't gotten around to it yet. Use of these types can crash the compiler or the runtime.
For an example of an infinitary type that crashes the compiler, see my article:
To Infinity But Not Beyond
Here's one. Cut n paste this code into Visual Studio and you'll see that this interface cannot be implemented:
interface ΙAmAPerfectlyOrdinaryInterface { }
class C : IAmAPerfectlyOrdinaryInterface { }
As long as we're talking trivia, I think this is a valid implementation of Eric Lippert's attempt:
class Program
{
static void Main(string[] args)
{
D test = new D();
}
}
class C
{
private C() { }
}
interface IFoo<T> where T : C, new() { }
class D : C
{
public D()
: this(5) { }
public D(int x)
: this() { }
}
class Dfoo : IFoo<D> { }
It compiles fine but crashes with a StackOverflowException when you instantiate D.
If you're trying to factor out an old interface you could mark the interface with the ObsoleteAttribute attribute.
Edit: as #Magnus noted in the comments, if you set the Error attribute to true it's usage will cause an error.
If a type is accessible and unsealed, it will be possible for outside code to create instances of that type and there isn't really anything the base type can do about it. No "full trust" or Reflection required.
public class CantDeriveMe
{
private CantDeriveMe()
{
}
public override string ToString()
{
return "My type is " + this.GetType().ToString();
}
}
public class OhYeah : CantDeriveMe
{
static OhYeah CapturedInstance;
~OhYeah()
{
CapturedInstance = this;
}
OhYeah() : this(1/String.Empty.Length)
{
}
OhYeah(int blah) : this()
{
}
public static OhYeah Create()
{
try
{
new OhYeah(4);
}
catch (DivideByZeroException)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
return CapturedInstance;
}
public static void test()
{
OhYeah it;
it = OhYeah.Create();
Console.WriteLine("Result was ({0})", it);
}
}
Note that if code is written only in C#, a base-class destructor might squawk if it notices that the object isn't of a legitimate type, but code written in languages other than C# would allow the override of Finalize to exit without chaining to its parent.
I think it's possible to specify an open generic interface with a combination of struct and class constraints which no combination of types could possibly fulfill, e.g.
public interface evil<T, U>
where T : struct,U
where U : class
I'm not sure whether such an open-generic type would really qualify as an "interface", though, or whether only closed generic types can really qualify as interfaces (or classes, or structs).

Categories

Resources