C# WPF application: What is "this"? - c#

I have been playing a lot with WPF applications in C# and there are a lot of things that are not really clear to me, I have been trying to look it up and play around with it to figure it out but without much success since english is my second tongue and I am still not that good with terminology nor with programming...
1: What is "this" in the main class? When I create the new WPF application in XAML I get window and a grid. However, I dislike XAML greatly and like to write code for all the elements and objects that I need so I delete that first grid, make a class, define my grid and to add it I have to write something like
this.AddChild(myGrid);
which is fine, but if I want to use "this" from my main class in other classes, it becomes a bit complicated to me. So, which UIElement or Object is "this"? How do I define it so it can be used in methods? "this", I suppose refers to the Window that is created at beginning, but what UIElement or Object is that Window?
2: Extended classes?? I have been watching a lot of java tutorials lately, simply to learn more about programming. There, to use the objects from other class you can simply write:
public class class1 extends class2{}
and everything is perfect, I have found out that I can mimic that same thing in C# WPF unless it's the main class, since main class extends :Window and I guess since it's defined as partial class... Is there a way to "extend" multiple classes or go around this?
Any help on clearing this up would be great :)

You should learn Object Oriented Programming in C#
this means the current instance of the class. So in each class this refers to a different object. this can usually be omitted and just AddChild(myGrid) can be used.
extends (or : in C#) means that the first class (class1) inherits from the second (class2) thus having access to methods and variables that are defined in class2 that are not marked private.

For the part about 'this' and its identity, the Window sits in a hierarchy of classes and can assume the identity of any of its ancestors. For example...
public MainWindow()
{
InitializeComponent();
var contentControl = this as ContentControl;
var control = this as Control;
var frameworkElement = this as FrameworkElement;
var uiElement = this as UIElement;
var dependencyObject = this as DependencyObject;
var dispatcher = this as DispatcherObject;
}
...all of the assignments in this snippet are legal. Also, there are more exotic assignments such as
var x = this as IInputElement;
The key here is to examine the framework and the various assignments available to each class. As others have pointed out, offline reading is essential to a quick learning curve.
The etymology of 'this' as a keyword in an object oriented context extends back to the late 1970's when it first appeared in an early specification for C++.
Finally, Xaml is one of the most attractive features of WPF for lots of reasons, and if Xaml isn't compatible with your approach, you MIGHT be better off in WinForms or Swing or similar tightly bound framework.

Simply said this is the class you are in.
For an example
class dim
{
int sum = 0;
public void num(int sum){
this.sum = sum; //Places the sum from num to the sum in dim
}
}

Extending a class is basically termed as Inheritance in Object Oriented Programming. There are several types of inheritance like single,multiple,multi-level,hierarchial,hybrid.But C# and also Java doesn't support inhertance from more than one class, because multiple inheritance creates a lot of ambiguity.
A feature that replaces multiple inheritance is the use of interfaces. Instead of 'extending from a class' we 'implement an interface' using the keyword 'implements'.An interface is just a skeleton class where you declare method signatures and the interface will be implemented in the class where you 'implement the interface'.The important point is you can implement more than one interface
To get an overview about Inheritance and Interfaces,the following link would be helpful:
http://msdn.microsoft.com/en-us/library/ms228387(v=vs.80).aspx

Related

Extending a class with a new nested class

first question so I'm open to advice on effectively participating in the StackOverflow community as well as pertaining to the question.
I'm working on a text-based UI in C#. I have an abstract window class and an abstract control class, each of which implements common functionality for the types that inherit them (e.g. pop-up windows or text box controls). Currently, within a program that might implement the library, a developer would have to create window objects and control objects, and then add the controls to their respective windows, and the windows to a window manager class, like this:
var mainWindow = new MainWindow(...);
var textBox1 = new TextBox(...);
mainWindow.AddControl(textBox1);
WindowManager.Add(mainWindow);
This works, but it's a bit clunky. Since a control should never have to exist outside of a window, I was hoping to implement the control types as nested types. However, to maintain extensibility of the program, I'd like for there to be a way to extend the window class with new control types. My question is this: Should I use reflection, or rely on developers using container classes to extend the window class? Alternatively, is there a better way to structure the program than how it's currently laid out?
I've also considered using generics, e.g.:
public abstract class Window : DrawableObject, IWindow
{
public void AddControl <T>(object[] constructorArgs) where T : class, IControl
{
}
}
I'm aiming for ease of implementation without sacrificing extensibility/loose coupling. Thanks in advance for any thoughts!
EDIT: Should clarify, the primary reason for this is to fix some weirdness with how Windows and Controls cooperate. Each control has a parentWindow property which is used to access the window on which a control resides, for various purposes like creating an exit button for a particular window, etc.
Right now, this property is passed to the constructor, but that seems redundant to me since after doing so you have to add the control to the window's control list. I'd like to find a way to set this property when the control is added to a window instead, but restrict this action to when the control is added only, to prevent potential problems if the parentWindow property is changed outside of this context.
The way you coded AddControl method:
public void AddControl <T>(object[] constructorArgs)
where T : class, IControl
{
}
You intend developers to just provide type and your AddControl method will create an instance of it using constructorArgs. This method itself implicitly forces you to use reflection. Anything else does not stand a chance. Because To Add control of type T, Creating Instance of Control of type T is necessary. Since your Window class does not have a clue about T reflection is the only solution.
To facilitate other approaches, you might want to consider few overloads of AddControl.
public virtual T AddControl <T>()
where T : class, new(),IControl
{
//now you can create instance no reflection required
var control = new T();
this.Controls.Add(control);
return control;
}
public void AddControl <T>(T control)
where T : class, IControl
{
}
public abstract void AddControl <T>(object[] constructorArgs)
where T : class, IControl;
Creating an abstract method passes onus of implementation on child class and creating new instance of T can be handled the assuming type of T is known there or at-least all cases of known types of what T might be are handled.
It's a wide scope topic and I guess subjective as well. The best use of OOP is to achieve a design which fits your logical objective whatever that maybe.

Understanding Interfaces in OOP

I am trying to learn OOP concept at an advance level. I was reading through the topic interfaces and have a confusion. But first, let me show you what exactly caused this confusion.
I tested this Code Sample. but I am confused with the use of interfaces. After implementing that code, it seems to me that I can call the method DoFirst from class A by simply creating an instance of it. so why use an interface at first place?
Something like this:
A myA = new A();
myA.DoFirst();
and similiarly,
B myB = new B();
myB.DoFirst();
In both the classes, i have to implement a method called 'DoFirst', so what good does interface provided to me?
Can't I just write these methods in different classes myself?
my Second question, say I have an interface that has 5 methods. If a class implements it, and only wants to provide implementation of 3 methods instead of writing code of all 5 methods supplied by the interface. Isn't this useless? why have access methods that i don't want?
can somebody answer these with example (Highly appreciated) please?
The advantage was already pointed out in the link you provided...
Basically you can also write
void DoSomething(IMyInterface obj)
{
obj.DoFirst();
}
And then send any type of object which implements that interface as a parameter.
A myA = new A();
DoSomething(myA);
B myB = new B();
DoSomething(myB);
The method DoSomethig doesn't care about the object's type, as long as it exposes an interface called IMyInterface.
Some Real Life examples - also, another way/reason to use interfaces.
In my own code I have an Engine which processes code to produce reports in Excel. In this engine, i had to write the code two different ways, one using the Microsoft Excel Interop, the other using the Open Office Interop. Rather than duplicate my entire engine to work two different ways, or write a lot of if statements in all the actual interop functions, I implemented an interface. Then I declared two classes, each one implementing the interface, but one uses Excel and the other uses open office. Then, in my code, I simple reference the interface and its functions and use a single if statement at the very beginning of the function to tell the interface which class to implement.
public class ExcelEngineInterop : ISSinterface
{ ... }
public class OOEngineInterop : ISSinterface
{ ... }
//cant use two variables with the same name, so use 1 interface reference instead
ISSinterface ssInt;
if(ExcelFlag)
ssInt = new ExcelEngineInterop();
else
ssInt = new OOEngineInterop();
//two VERY different functions between Excel and OpenOffice.
ssInt.OpenApp();
ssInt.OpenFile(fileName);
//etc etc and so on
This is the other reason to use an interface. When you need one block of code to act two (or more) different ways depending on some external flag.
Another Example.
There is a top level form with lots of custom user controls under it. The user fires a form level event, like a button click, but depending on which user controls are active and what settings are on them at the time the click happens, the controls themselves need to do something different. Rather than writing what could be a rediculously large number of if statements to make sure each one acts correctly from the top level, just implement an interface on each control, then do something like this:
public ButtonClick(object sender, EventArgs e)
{
//note: I dont know which of my classes currentrightcontrol belongs to at the moment.
// it could be any one of 22 different controls. It must be cast to something
// in order to call the ButtonClick method (its actual type is generic "UserControl"
IMyRunControl ctrl = CurrentRightControl as IMyRunControl;
ctrl.FormButtonClicked();
}
C# is a statically typed language (at least unless you explicitly tell it not to be). This means that the compiler uses the type of the variable to know whether the referenced object has the members you are about to use.
The interface, therefore, provides a contract to the compiler (and to other programmers, too) that this class implements that interface. Because interfaces can be shared across classes that don't have a hierarchical relationship, this means that you can define a method that can take an object as an argument by defining that interface in the parameter type.

Binding a (complex) class property to CF.NET in C#

I am trying to make a 2-way binding of a class property.
public class MyClass{
public MyField AField1{get;set;};
public MyField AField2{get;set;};
}
public class MyField{
public string Value {get; set}
}
MyClass _class = MyClass();
_dv.DataSource = _class;
Databinding text object displays MyField class name instead of Value Property. I also tried to enter:
DataMember = "AField1.Value";
Is there any way to bind (2-way) AField1.Value of a class MyClass to a visual control?
It's a pain. There's no built-in way to achieve this in .NET, so I can safely say, even less in the CF.
You can get started with this article on MSDN Blogs, but it's pretty limited as you can only get one level of nested property bindings.
Personnally, I ended up writing a custom BindingSource, based on code that lies somewhere on the internets. I can't give you source code of my rewrite as it's property of my employer, but here's the link to the project that got me started.
There are a few drawbacks to the code provided : some of his namespaces are System.ComponentModel, and VS2010 didn't seem to like, so I had to rename them. And a few more issues in design time that can make it a pain to use (so you'll want to fix that too), like loosing the list of properties when you make a spelling mistake and so on...
But it's the best shot (IMHO) at creating a good BindingSource that handles nested objects, and you'll get the idea of what needs to be done to achieve your nested bindings.
The last drawback (and biggest probably, but I have no experience with CF) is that the project is written for the regular .NET Framework, so it's likely that you will have to rewrite it entirely.
Hope that helps....
Edit. Uh oh, I've been grave-digging without noticing... sorry.
PS. Another idea is to simply create one binding source for each of your nested objects, but it gets messy (IMO) if your object hierarchy is complex.

C# has abstract classes and interfaces, should it also have "mixins"?

Every so often, I run into a case where I want a collection of classes all to possess similar logic. For example, maybe I want both a Bird and an Airplane to be able to Fly(). If you're thinking "strategy pattern", I would agree, but even with strategy, it's sometimes impossible to avoid duplicating code.
For example, let's say the following apply (and this is very similar to a real situation I recently encountered):
Both Bird and Airplane need to hold an instance of an object that implements IFlyBehavior.
Both Bird and Airplane need to ask the IFlyBehavior instance to Fly() when OnReadyToFly() is called.
Both Bird and Airplane need to ask the IFlyBehavior instance to Land() when OnReadyToLand() is called.
OnReadyToFly() and OnReadyToLand() are private.
Bird inherits Animal and Airplane inherits PeopleMover.
Now, let's say we later add Moth, HotAirBalloon, and 16 other objects, and let's say they all follow the same pattern.
We're now going to need 20 copies of the following code:
private IFlyBehavior _flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
private void OnReadyToLand()
{
_flyBehavior.Land();
}
Two things I don't like about this:
It's not very DRY (the same nine lines of code are repeated over and over again). If we discovered a bug or added a BankRight() to IFlyBehavior, we would need to propogate the changes to all 20 classes.
There's not any way to enforce that all 20 classes implement this repetitive internal logic consistently. We can't use an interface because interfaces only permit public members. We can't use an abstract base class because the objects already inherit base classes, and C# doesn't allow multiple inheritance (and even if the classes didn't already inherit classes, we might later wish to add a new behavior that implements, say, ICrashable, so an abstract base class is not always going to be a viable solution).
What if...?
What if C# had a new construct, say pattern or template or [fill in your idea here], that worked like an interface, but allowed you to put private or protected access modifiers on the members? You would still need to provide an implementation for each class, but if your class implemented the PFlyable pattern, you would at least have a way to enforce that every class had the necessary boilerplate code to call Fly() and Land(). And, with a modern IDE like Visual Studio, you'd be able to automatically generate the code using the "Implement Pattern" command.
Personally, I think it would make more sense to just expand the meaning of interface to cover any contract, whether internal (private/protected) or external (public), but I suggested adding a whole new construct first because people seem to be very adamant about the meaning of the word "interface", and I didn't want semantics to become the focus of people's answers.
Questions:
Regardless of what you call it, I'd like to know whether the feature I'm suggesting here makes sense. Do we need some way to handle cases where we can't abstract away as much code as we'd like, due to the need for restrictive access modifiers or for reasons outside of the programmer's control?
Update
From AakashM's comment, I believe there is already a name for the feature I'm requesting: a Mixin. So, I guess my question can be shortened to: "Should C# allow Mixins?"
The problem you describe could be solved using the Visitor pattern (everything can be solved using the Visitor pattern, so beware! )
The visitor pattern lets you move the implementation logic towards a new class. That way you do not need a base class, and a visitor works extremely well over different inheritance trees.
To sum up:
New functionality does not need to be added to all different types
The call to the visitor can be pulled up to the root of each class hierarchy
For a reference, see the Visitor pattern
Cant we use extension methods for this
public static void OnReadyToFly(this IFlyBehavior flyBehavior)
{
_flyBehavior.Fly()
}
This mimics the functionality you wanted (or Mixins)
Visual Studio already offers this in 'poor mans form' with code snippets. Also, with the refactoring tools a la ReSharper (and maybe even the native refactoring support in Visual Studio), you get a long way in ensuring consistency.
[EDIT: I didn't think of Extension methods, this approach brings you even further (you only need to keep the _flyBehaviour as a private variable). This makes the rest of my answer probably obsolete...]
However; just for the sake of the discussion: how could this be improved? Here's my suggestion.
One could imagine something like the following to be supported by a future version of the C# compiler:
// keyword 'pattern' marks the code as eligible for inclusion in other classes
pattern WithFlyBehaviour
{
private IFlyBehavior_flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
[patternmethod]
private void OnReadyToLand()
{
_flyBehavior.Land();
}
}
Which you could use then something like:
// probably the attribute syntax can not be reused here, but you get the point
[UsePattern(FlyBehaviour)]
class FlyingAnimal
{
public void SetReadyToFly(bool ready)
{
_readyToFly = ready;
if (ready) OnReadyToFly(); // OnReadyToFly() callable, although not explicitly present in FlyingAnimal
}
}
Would this be an improvement? Probably. Is it really worth it? Maybe...
You just described aspect oriented programming.
One popular AOP implementation for C# seems to be PostSharp (Main site seems to be down/not working for me though, this is the direct "About" page).
To follow up on the comment: I'm not sure if PostSharp supports it, but I think you are talking about this part of AOP:
Inter-type declarations provide a way
to express crosscutting concerns
affecting the structure of modules.
Also known as open classes, this
enables programmers to declare in one
place members or parents of another
class, typically in order to combine
all the code related to a concern in
one aspect.
Could you get this sort of behavior by using the new ExpandoObject in .NET 4.0?
Scala traits were developed to address this kind of scenario. There's also some research to include traits in C#.
UPDATE: I created my own experiment to have roles in C#. Take a look.
I will use extension methods to implement the behaviour as the code shows.
Let Bird and Plane objects implement a property for IFlyBehavior object for an interface IFlyer
public interface IFlyer
{
public IFlyBehavior FlyBehavior
}
public Bird : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
public Airplane : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
Create an extension class for IFlyer
public IFlyerExtensions
{
public void OnReadyToFly(this IFlyer flyer)
{
flyer.FlyBehavior.Fly();
}
public void OnReadyToLand(this IFlyer flyer)
{
flyer.FlyBehavior.Land();
}
}

Class declared inside of another class in C#

I am working on some legacy code and have come across something that I'm not sure of. We have a class y that is declared inside of another class x. Class y is only ever used inside of class x but my question is why wouldn't you create a separate class file and put class y in there instead of declaring it inside of class x? Isn't this violating OOP's or is it just a matter of style since it is only ever used inside of this class. I'm refactoring some of this code and my first reaction would be to separate class y out into it's own file.
namespace Library
{
public class x
{
// methods, properties, local members of class x
class y
{
// methods, properties, local members of class y
}
}
}
You create an inner class because it is only ever used within the scope of class x and it logically fits in the factoring/architecture of class x.
Class y might also be privy to implementation details of class x that are not meant to be known to the public.
This has permissions implications. A top-level "class y" would be "internal" - however, here "y" is private to "x". This approach is helpful for implementation details (for example cache rows etc). Likewise, y has access to all private state of x.
There are also implications with generics; x<T>.y is generic "of T", inherited from the outer class. You can see this here, where Bar has full use of T - and note that any static fields of Bar are scoped per-T.
class Foo<T> {
void Test(T value) {
Bar bar = new Bar();
bar.Value = value;
}
class Bar {
public T Value { get; set; }
}
}
Often people incorrectly think they need to define Bar as Bar<T> - this is now (effectively) doubly generic - i.e. Foo<TOld, T> - where TOld is the (now unavailable) T from Foo<T>. So don't do that! Or if you want it to be doubly-generic, pick different names. Fortunately, the compiler warns you about this...
This code is fine for the exact reason that you have given - "class y is only ever used inside of class x". Those are nested types and one of the guidelines for using them is that nested types should be tightly coupled to their declaring type and must not be useful as a general purpose type. That way the nested class is inacessible to other classes, but still allows you to follow object oriented principles.
I just went through code that I am updating (and I originally wrote) and removed all nested classes. Unfortunately, I originally used the nested class outside of the class it was defined in. Moving nested classes out made a huge difference to me because I originally had bad design.
If Y is only used in X and will never be used outside of X, I'd say keep it there
I think it's ok, as long as the contained class is only used as utility. I use this sort of construct for example to define complex return types for private methods.
Let me give you an example of the use of nested classes that might clarify when this kind of architecture is appropriate. I recently needed to generate an HTML table by pulling selected columns from a data table and "pivoting" them so that rows become columns and vice versa. In my case, there were two essential operations: pivoting the data and generating some rather complex output (I was not just showing the data: each data column/table row was subject to operations for extracting title, generating image tags, setting up links, etc. thus using a SQL Pivot wasn't really right either).
After an initial attempt to create one class to do the whole thing, I recognized that much of the data/methods fell into three distinct partitions: header processing, row processing, and pivoting. Thus, I decided that a better approach would be to encapsulate the logic for "header" and "row" into separate, nested classes. This allowed me to separate the data held by each row and program the pivot operations very cleanly (calling a separate row object for each column in your data table). At the end of the pivot operations, I generated output by calling the header object and then each row object in turn to generate its output back to the main class.
Separate classes weren't appropriate because A) the nested classes did need some data from the master class and B) the processing was very specific and not useful elsewhere. Just programming one big class was simply messier due to confusion surrounding terms such as "column" and "row" which differed depending on whether you were talking about data or HTML output. Also, this was unusual work in that I was generating HTML in my business class so I wanted to pull apart the pure business logic from the UI generation. In the end, nested classes provided the perfect balance, then, of encapsulation and data sharing.
You could still refactor your class y into another file, but use a parial class. The benefit of this is that you still have one class per file and don't have the refactoring hassles of moving the declaration outside of class x.
e.g. you could have a code file: x.y.cs which would look something like
partial class X
{
class Y
{
//implementation goes here
}
}

Categories