C# code want perfect output and justification [closed] - c#-3.0

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
class Base
{
public virtual void Method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void Method()
{
Console.WriteLine("Derived method");
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.Method(); // Displays 'Base Method'
Console.ReadLine();
}
}
what should be the output?
how it come? please explain

The output should be, and is, `Derived Method." When you override a method in a derived class, you are changing the implementation of that method for any instance of the class.
So, even though you are referencing b1 as a Base, the runtime knows it is in fact an instance of Derived and will use the latter's implementation.

It will display the "Derived Method" . now come to the code , what exactly you are doing in Class Myclient .See you are creating a object of B class with Derived class constructor.so run time will go through derived class ,and cretae an instance of derived class .and result will be the "Derived method"

Related

Why can't I call a method from another class?

I have two classes, E and F.
In class F, I'm trying to call the method which I created in class E called printData(), but I'm unable to call it. There is an error which says 'printData cannot be resolved or is not a field'. What is the reason? See the screenshots below. I did import the package as well(import login.*;)
package login;
public class E {
public void printData {
System.out.println("Hello...");
}
}
Class E
package testing;
import login.*;
public class F {
public void main(String[] args) {
B b = new B();
b.printData
}
}
Class F
In case it is not clear from my comment, your mistake is that in your main method of class F, you are creating an object of class B, which clearly does not have a public method printData, as opposed to class E, which does.
As this is basically a typo, I am voting to close this question, as it is of very little use to other users. You should not be disheartened, if the question is closed. This is normal behaviour on this site, to try to restrict the size of the repository of questions and answers to ones, which would be of greater use to more people.
I have included your code within the body of the question (as you should have done). People here do not appreciate images, as they cannot be copied. This also makes it clearer than you have a syntax error in calling the method: you need b.printData();. Without the parentheses, the compiler takes printData to be a field, not a method, hence the nature of your error message.

Dagger 2 - How #ContributesAndroidInjector behaves when another provision method depends on its return type [duplicate]

This question already has answers here:
Why #ContributesAndroidInjector doesn't provide Android Framework type
(2 answers)
Closed 3 years ago.
I have two provision methods, one depending on the object the other method provides. Below code works properly the problem is stated under the section of Problem
Working Example
In StringProviderModule, added a method which is dependent on the object (Fragment instance) provided in the parent component.
#Module
class StringProviderModule {
#Module
companion object{
#JvmStatic
#Provides
fun provideFragmentArgument(cripledFragment: CripledFragment): String{
return cripledFragment.arguments?.getString(CripledFragment.ARG_STRING) ?: "No such argument"
}
}
}
In FragmentModule, added StringProviderModule to FragmentModule's generated subcomponent
#Module
abstract class FragmentModule {
#ContributesAndroidInjector(modules = [StringProviderModule::class])
abstract fun fragment: CripledFragment
}
In ActivityBinderModule, adding FragmentModule to the ActivityBinderModule's generated subcomponent
#Module
abstract class ActivityBinderModule {
#ContributesAndroidInjector(modules = [FragmentModule::class])
abstract fun mainActivity(): MainActivity
}
In AppComponent, adding ActivityBinderModule as a module
#Component(modules = [
AndroidSupportInjectionModule::class,
ActivityBinderModule::class
])
interface AppComponent: AndroidInjector<DaggerMyApp> {
#Component.Builder
interface Builder{
#BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
}
Then #Injecting String into Presenter class and #Injecting that presenter into CripledFragment. I can access Fragment's String argument in Presenter. Implementation is not important as it's outside the scope of the question, I can add code if needed, though.
Problem
When merging StringProviderModule and FragmentModule, IDE complains with following message "CripledFragment cannot be provided without an #Inject constructor or an #Provides-annotated method". Isn't #ContributesAndroidInjector already providing an instance of CripledFragment?
#Module
abstract class FragmentModule {
#ContributesAndroidInjector
abstract fun cripledFragment(): CripledFragment
#Module
companion object{
#JvmStatic
#Provides
fun provideFragmentArgument(cripledFragment: CripledFragment): String{
return cripledFragment.arguments?.getString(CripledFragment.ARG_STRING) ?: "No such argument"
}
}
}
I have checked multiple tutorials and dagger docs, couldn't find any proper explanation to infer the cause of my problem. Simple explanation rather than suggesting a solution is much appreciated as I'm not looking for a concrete solution.
This question has been answered here. Basically, #ContributesAndroidInjector provides MainActivity instance for a subcomponent it generates not for a module (in this case ActivityBinderModule) it resides in. That means any provision method inside FragmentModule will have access to MainActivity's instance.
#Module
abstract class ActivityBinderModule {
#ContributesAndroidInjector(modules = [FragmentModule::class])
abstract fun mainActivity(): MainActivity
}

How to deal with polymorphism inside a class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In languages with dynamic typing, the use of polymorphism may trigger errors on a super-class.
I will try to explain my question with a simple example:
Supposing a language with dynamic typing (like ECMAScript) and the following class structure:
class A{
private idA;
public A(){
idA=0;
}
public foo(){
update();
if (this.idA!=3) Throws new Exception(" What is happening? ");
}
private update(){
this.idA = 3;
}
}
class B extends A{
private idB;
public B(){
super();
idB=0;
}
public foo(){
super.foo();
// Any operation between A::update and B::update()
if (this.idB!=0) Throws new Exception("hmmm, that could not happend!");
update();
}
private update(){
this.idB = 5;
}
}
In this very simple example, when i create an object of the class B, B::foo() call the parent A::foo(), which call "update". The object is an instance of B, so the "update" functions called is B::update, after that, in B::foo, the update function is again called (B::update). The final result is that A::update is never called, and idA still 0.
The class A work correctly when used alone, but after to extend it with B, the function foo() fail.
What is the correct solution this problem:
1) Force the class A to call A::update , that mean an ugly code every call to his own function (protect the super-class):
A::foo(){
A::update();
if (this.idA!=3) Throws new Exception(" What is happening? ");
}
2) B::update is an extension of A::update, so B::update must call itself the parent function (prepare the sub-class, and deal with problems):
B::foo(){
super.foo();
... // Any operation that must be performed between A::update and B::update
}
B::update(){
super.update();
this.idB = 5;
}
But in this case is the A::foo which call update, not the B::foo. That mean others problems.
3) Any other solution.
As a summary:
How to protect the super-class code against polymorphism?
Add protections into the super-class.
Deal with these problem creating the child-class
The language must do that! (do not know if it is possible with dynamically typed languages)
I am looking for a very theoretical /canonical solution to this question.
EDITED: to take the problem out of the constructor and clarify some points.
It's generally considered a very bad practice to call instance methods, and especially virtual instance methods from within a constructor exactly for this reason (but also for the reason that the object isn't done being "initialized" yet).
3) Any other solution.
Doc, it hurts when I do this.
Then don't do that!
Seriously, if you need to set IdA in the constructor of A, don't do it by calling update, do it by explicitly setting the value of IdA in the constructor for A.
The base class should protect itself from harmful overrides. In keeping with the open/close principle, it should be open to extension but closed to modification. Overriding update is a harmful modification of the base class's intended behaviour. In your example, there is no benefit in overriding update because both A::update and B::update are private methods that deal with private variables. There isn't even an expectation that they should be executed together judging by your exception in B::foo. If B::update was named differently, there wouldn't be anything wrong with your implementation. It would probably be OK anyway: since no language I know of will let you override a private method, B::update could hide A::update rather than overriding it.
Depending on the language, you can limit which methods can be overridden in different ways. Some languages require an indicator (a keyword or attribute usually) that a method can be overridden, others to show that it can't. Private methods are generally not overridable, but not all languages have access modifiers at all, and everything is effectively public. In this case you would have to use some kind of convention as suggested by #PoByBolek.
tl;dr: Children have no business with their parents' privates.
You're probably not going to like my answer but: convention and disciplin.
Establish conventions for
when it is safe for a child class to override a method without calling the parent class implementation,
when a child class has to call the parent class implementation of an overridden method,
when a child class must not override a parent class method.
Document these conventions and stick to them. They should probably be part of your code; either in form of comments or naming conventions (whatever works for you). I could think of something like this:
/*
* #final
*/
function shouldNotBeOverridden() {
}
/*
* #overridable
* #call-super
*/
function canBeOverriddenButShouldBeCalledFromChildClasses() {
}
/*
* #overridable
*/
function canBeOverridenWithoutBeingCalledFromChildClasses() {
}
This may help someone reading your code to figure out which methods he may or may not override.
And if someone still overrides your #final methods, you hopefully have thorough testing ;)
I like this answer to a somewhat similar question regarding python:
You could put a comment in there to the effect of:
# We'll fire you if you override this method.
If the language allows one class to call a private method of another class this way, the programmer has to understand and live with that. If I'm understanding your objective, foo and update should be overridden and update should be protected. They would then call the method in the parent class, when necessary. The derived foo method wouldn't need to call update, because calling foo in the parent class would take care of that. The code could work like this:
class A{
private idA;
public A(){
idA=0;
}
public foo(){
update();
if (this.idA!=3) Throws new Exception("idA not set by update");
}
protected update(){
this.idA = 3;
}
}
class B extends A{
private idB;
public B(){
super();
idB=0;
}
#Override
public foo(){
super.foo();
// Any operation between A::update and B::update()
if (this.idB!=5) Throws new Exception("idB not set by super.foo");
}
#Override
protected update(){
super.Update()
this.idB = 5;
}
}
I changed the exceptions to match expectations.

MVVM: Does the state of the model belong in the model or the viewmodel? [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 am building an application that will be based on MVVM.
I have resolved most of my design issues, but I am left with a conceptually crucial one:
Should my ViewModel or my Model contain the state of what ever the Model models?
Initially I thought that the Model should contain its own state, but it turns out that there is a lot of boilerplate involved when passing the state to the ViewModel (which has 90% of the Model's state).
Then I though about move the entire state from the Model to the ViewModel, but this doesn't sit quite right with me, as I conceptually perceive the ViewModel as having the state of the View more than the state of the Model.
What is most accepted place to put the state?
You are correct perceiving the ViewModel having the state of the view. Conceptually, the state of the model is part of the model, but it may varies depends on your specific scenario. Think of the Model as data: as something that can be serialized, can come from the server and/or can/should be persisted in a database.
If for example you have a shopping cart, then the items of the shipping cart is obviously part of the model. However, the state in the check-out process (payment method received, payment method verified, user confirmed) can go either way.
As for the boilerplate - the paradigm that works well for me with reasonable amount of boiler plate is containing (actually, referencing in c#) the entire Model within the ViewModel, and exposing getters and setters for all properties in the Model, with the appropriate even notification. e.g.
class PersonModel {
public string firstName { get; set; }
public string lastName { get; set; }
}
class PersonViewModel : INotifyPropertyChanged {
private PersonModel model;
// next 4 lines can be factored out to a BaseViewModel class
private PropertyChangedEventHandler PropertyChanged;
private raise(string propName) {
this.PropertyChanged( new PropertyChangedEventArgs(propName) );
}
// ... repeat for each property in the model
public string firstName {
get { return model.fistName; }
set { model.firstName = value; raise('firstName'); }
}
public string lastName {
get { return model.lastName; }
set { model.lastName = value; raise('lastName'); }
}
}

What is the best usage of Dispose for "Entity Framework"?

What is the true usage of dispose ?
This is first (my) approach:
public class RequestService : IDisposable
{
requestDBEntities db;
public RequestService() //Constructor
{
db = new requestDBEntities ();
}
public List<RequestStatus> ddlFill()
{
return (from rs in db.reqStatus select rs).ToList();
}
//Some Insert,Update,Delete methods {}...
public void Dispose()
{
db.Dispose(); //<--Dispose requestDBEntities();
GC.SuppressFinalize(this);
}
And second approach:
public class RequestService : IDisposable
{
requestDBEntities db;
public List<RequestStatus> ddlFill()
{
using (db = new requestDBEntities())
return (from rs in db.reqStatus select rs).ToList();
}
//Some Insert,Update,Delete methods {}...
public void Dispose()
{
GC.SuppressFinalize(this);
}
Page Code-behind:
using (RequestService _reqService = new RequestService ())
{
ddlRequestStatus.DataSource = _reqService.ddlFill();
ddlRequestStatus.DataBind();
//Some Insert,Update,Delete operations...
}
Thank you..
It's difficult (impossible) to say which is the better approach, since we don't know your exact design choice. From the perspective of a simple app, it may seem that the two examples are equivalent (more or less), but they really do behave in entirely different ways.
The fundamental question here is: Should the lifetime of db be comparable to the lifetime of its enclosing RequestService instance?
If yes, then the first code example is the way to do things. Resources will be managed as expected (db disposes its stuff at the same time the RequestService object is asked to dispose of its resources), and the lifetime of the two will be pretty much identical (db is constructed in the RequestService constructor, and db become collectable as soon as its RequestService object becomes collectable).
However, if the answer is "no", then the second example is (almost) the way to do things - since you generate a collection view of the RequestStatus object from db, you really have no reason to keep db around any longer. However, to make this a bit better, may I suggest restricting the scope of db to within the ddlFill method:
public List<RequestStatus> ddlFill()
{
using (var db = new requestDBEntities())
return (from rs in db.reqStatus select rs).ToList();
}
No need for an extraneous class member when a stack value suffices.
What for in second example you have declared requestDBEntities db; at class level instead of having it as a stack variable?
Comparing your approaches, the question is - are you ready to create requestDBEntities on each call? If you are - second approach is better, in fact if there is nothing else you haven'y posted - you don't need dispose at all. But you'll have extra time penalty on instantiating/releasing requestDBEntities on each call.