This question already has answers here:
In C#, what is the difference between public, private, protected, and having no access modifier?
(19 answers)
Closed 7 years ago.
I'm beginning to learn C# and I come from a C++ background. The example page I was supposed to create by these instructions looks like
using System.Web;
using System.Web.Mvc;
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my <b>default</b> action...";
}
//
// GET: /HelloWorld/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
}
}
My main question is why the HelloWorldController class is prefixed by public. I understand that HelloWorldController is derived from Controller, but why does a class need to be public in the first place? My understanding of the words public and private is that they only have meaning if they're functions inside a class, and that public are the ones that can be used by instances of that class. Also, where is my main.cs in this Visual Studio ASP.NET MVC project that I created?
The purpose of public and private on a class differs from that on methods.
Classes (C# Programming Guide)
public class Customer
{
//Fields, properties, methods and events go here...
}
The class keyword is preceded by the access level. Because public is
used in this case, anyone can create objects from this class.
Access Modifiers (C# Programming Guide)
public class Bicycle
{
public void Pedal() { }
}
The type or member can be accessed by any other code in the same
assembly or another assembly that references it.
A private class wouldn't be able to be used by anything, unless it were within another class. C# doesn't allow un-nested classes to be private, as nothing could use it.
However, there is another option: you could mark the class as internal instead. internal restricts access to within the current assembly.
The keyword indicates who is allowed to create instances (objects) from this class. Private would be used if you have classes nested inside each other, and you don't won't it accessible from outside the class.
From MSDN
The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behaviour and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.
Related
I am new to programming and just now am going through OOPs concepts when I learned about "inheritance" (the process of deriving a new class from an already existing class).
When I opened a new project in asp.net I found this,
public partial class Master_Pages_Email_Template : System.Web.UI.Page
{
which means the class is inherited from page?
When I tried to remove the System.Web.UI.Page some of the code showed errors (ex: IsPostback).
But when in inheritance when I need to access the methods or member variable from a parent class, I have to create a instance isn't it?
But without creating an instance how does this code work?
Sorry if I am wrong..
When an instance of a derived class is created, an "instance" of the base class is created first. That is to say, the derived instance contains everything that would have been in a base instance. In fact, a derived instance is a instance of the base class.
Note that this is not specific to ASP.NET. ASP.NET pages are classes, so this is just normal OO.
If you are new to programming and OOP concepts then OOP has following main pillars.
1. Inheritance
2. encapsulation
3. polymorphism
4. Abstraction
You need to learn all these concepts in order to write any program in Object oriented way.
As far as your questions are concerned. Yes your class is inherited from page. and if you remove System.Web.UI.Page then you can't access method or properties of parent class. Because Inheritance is known as IS A relation.
So if you inherit Class A from Class B then you can access all method or properties of Class A in Class B. but do remember you can access properties or methods of parent class which are not defined as Private (Access Modifiers).
For details about OOP concepts please see. http://msdn.microsoft.com/en-us/library/ms173149.aspx
To understans Access Modifiers
When your class inherits from another class it gets all of the parent class's properties and methods and can use them as if they are its own, also can provide new implementation for these methods. You do not need to create an instance of the class in this case, instantiation is required only when you need to create an object of type class and to use its functionality... I would suggest you learn the basic C# clearly and then going for ASP.Net any such technologies because all of which are based on the base concepts..
PS: this guy got a good list of tutorials on these technologies.. http://www.youtube.com/user/kudvenkat/videos?flow=grid&view=1
A simple code snippet to demonstrate Inheritance and Accessibility.
public class Base
{
private int PrivateProperty { get; set; }
protected int ProtectedProperty { get; set; }
public bool PublicProperty { get; private set; }
}
public class Derived : Base
{
public void A_Method_Which_Need_BaseProperties()
{
if (this.PublicProperty) //Derived can access (only Read) Base PublicProperty
{
this.ProtectedProperty = 1; //Derived can access (Both Read and Write) Base ProtectedProperty
//this.PrivateProperty = 2; //You can't do this. Derived can not access Base PrivateProperty
}
}
}
This question already has answers here:
Why can't my public class extend an internal class?
(5 answers)
Closed 9 years ago.
See this code:
internal class c
{
private int d;
}
public class a : c
{
private int b;
}
Why can I not inherit a public class from an internal class? Why does the compiler have this behavior?
Because the public class would be visible outside your current assembly, while the internal one isn't. When deriving from a class you can only restrict visibility further, because in your case it would make the implementation of c available to consumers outside your assembly which kind of defeats the purpose of making the class internal in the first place.
You can use composition instead of inheritance, though.
C# design principle. Derived class should atleast have same accessibility as the parent class. In your case it is not hence not allowed. Take a look at Eric Lippert's view on this deriving public class from an internal class
Because "public class" is more "visible" than "internal class".
C# language has visibility protection layer that prevents this.
Internal classes can only be accessed from within the Assembly in which they are defined. When public class a inherits from an internal class in effect attempts to make the internal class public.
To avoid this encapsulate the internal class in the public class.
This question already has answers here:
Is it possible to have a private class?
(4 answers)
Closed 9 years ago.
Whats the difference between "Class" only and "Private Class" declaration in C#?
If these are nested classes, there's no difference:
namespace Foo
{
public class Outer
{
private class ExplicitlyPrivate {}
class ImplicitlyPrivate {}
}
}
Type members always default to being private.
If it's a top-level class, then you can't make it private - but the default is internal:
namespace Foo
{
class ClassIsInternalByDefault {}
}
When you declare a class without specifying an accessibility modifier it will default to the lowest accessibility possible.
More practically, specifying private when private is not permissible can result in a compilation error.
A simple answer is to say that a private class is meant to protect attributes within that class from being changed by any external classes, other than during construction of the program. A normal "class", well, doesn't have that protection.
It is a form of ENCAPSULATION.
(inspired by this comment)
Is there ever a situation in which you need to use the private keyword?
(In other words, a situation in which omitting the keyword would result in different behavior)
public class Foo
{
public int Bar { get; private set; }
}
Omitting the word 'private' would change the accessibility.
a situation in which omitting the keyword [private] would result in different behavior
David Yaw's answer gave the most usual situation. Here is another one:
In Account_generated.cs:
// Generated file. Do not edit!
public partial class Account
{
...
private partial class Helper
{
...
}
...
}
In AccountHandCoded.cs:
public partial class Account
{
...
public partial class Helper
{
...
}
...
}
The above code will not compile. The first "part" of Account requires the nested class Helper to be private. Therefore the attempt by the hand-coder to make Helper public must fail!
However, had the first part of the class simply omitted the private keyword, all would compile.
So for partial classes (and structs, interfaces), the access-level-free declaration
partial class Name
means "the other 'parts' of this class are allowed to decide what the accessibility should be".
Whereas explicitly giving the default accessibility (which is internal for non-nested types and private for nested ones) means "this class must have the most restricted access possible, and the other 'parts' cannot change that fact".
private isn't about the runtime behaviour. It's to make your application maintainable. What's hidden by private can only ever affect the code outside its class through the public or protected members.
So the answer is 'no' for runtime behaviour, 'yes' for developer behaviour!
In C# version 7.2 and later.
The private protected keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected
In my namespace I can have public classes which are accessible to all other pages in my namespace. How do I go about having public functions? Do I have to create a class with the functions in it? Or is there an easier way?
In C#, all functions (which are actually called methods in C# terminology) are to be declared in a type (a class or a struct).
However, there is the concept of static classes in C#, which are good for the purpose of replacing “global functions” in older programming languages:
public static class MyUtilityFunctions
{
public static void PrintHello()
{
Console.WriteLine("Hello World!");
}
}
Now you can, anywhere in your program, write:
MyUtilityFunctions.PrintHello();
A static method is a method that doesn’t require an object. A static class is a class that contains only static methods (and static fields, static properties etc.).
Functions (Methods) "live" in types, so you need to put them in classes or structs. By default they would be private so you need to specify the public access modifier for them to be accessible:
namespace myNameSpace
{
public class myClass
{
public void MyMethod()
{
}
}
}
See MSDN - Methods section of the C# programming guide.
When doing C#, functions can only live in types (classes and structures). You can not declare a function on its own.