|
If a class implements an interface, you know it contains specific items, functions or methods. You could of course also use abstract class to do it too.
|
|
|
|
|
They aren't "unneccessary" methods, they define the methods that must be implemented in order to use the Interface.
If you think of an Interface as a contract rather than a class, the properties and methods defined by the Interface are conditions attached to the contract that must be adhered to or the contract is broken.
One of the best examples is the IEnumerable interface which "allows" you to use your class in a foreach statement. It has the "condition" in its "contract" that your class must implement the GetEnumerator method, because that is what the foreach loop calls in order to iterate your class. If you don't implement it, the compiler will complain because the contract is "broken" and any foreach loop which tried to reference your class would fail.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
OriginalGriff wrote: the IEnumerable interface which "allows" you to use your class in a foreach statement ... If you don't implement it, the compiler will complain
Not entirely true.
The compiler actually uses a form of duck-typing, so that any type that has a GetEnumerator method which returns a type that has a suitable MoveNext method and a Current property can be used in a foreach loop.
It's a throwback to the pre-generics days of .NET 1.x, and was mainly intended to avoid the boxing overhead involved with enumerating collections of value types.
public struct DuckEnumerator
{
public bool MoveNext()
{
return true;
}
public string Current
{
get { return "Quack!"; }
}
}
public class Duck
{
public DuckEnumerator GetEnumerator()
{
return new DuckEnumerator();
}
}
int count = 0;
var donald = new Duck();
foreach (string value in donald)
{
Console.WriteLine(value);
if (++count > 42) break;
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
It's a "lies-to-children" example: Lies-To-Children - Discworld & Terry Pratchett Wiki[^]
The truth about foreach is more complicated than is needed when you are getting started with the concept of interfaces, so I didn't want to add to the confusion.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I think the choice of the word “interface” was a poor one in the first place since it conjures up one kind image (how to “communicate” with something), when I like to think of it more as a statement of code that is shared.
For example, there are different kinds of "horse races": maiden; maiden special weight; maiden claiming; claiming; optional claiming; allowance; stakes; handicap; etc.
Then there are “past performances”, which are races that have been run.
Programming against “races to be run” and “past performances” seems different enough, but they also have a lot in common when it comes to “consuming” them (as in a report), so we define an interface (e.g. IRace) so that any code that “uses” IRace “knows” that there will be available: a race date; track code; race#; horse name; etc.).
It doesn’t matter if the code in question is running against “today’s race” or a “past performance”, the code is content just to know that the thing has IRace behavior.
“Interfaces” supposedly are an alternative to “multiple inheritance” which C# doesn’t allow; but that’s another story. Also, deciding between refection, dynamics, “interface”, “inheritance”, “generics”, etc. or some combination thereof makes it all a bit less than simple, when it comes to writing "reusable / shared code".
|
|
|
|
|
So... they lead to a race condition.
This space for rent
|
|
|
|
|
Yes; but I like to tell people it's only a hobby.
|
|
|
|
|
Member 9730878 wrote: What is benefit of it? A short practical example; you'll see below code in some tutorials on the internet;
using (SqlConnection con = new SqlConnection("famousstringhere"))
using (SqlCommand cmd = con.CreateCommand())
{
..
} All those db-providers implement the same interface. In below code it is easier to swap the concrete class you're using;
using (IDbConnection con = new SqlConnection("famousstringhere"))
using (IDbCommand cmd = con.CreateCommand())
{
..
} It also means I can program against an interface that's already known, without having a specific class. Or have one injected by a framework. Or make that user-configurable
The difference in learning the benefit is like being bound to a single database, or have the user configure the database of their choice in a file.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Unfortunately, not the best example.
You could also swap out the concrete classes for their abstract base types (in System.Data.Common ), which gives you many of the same benefits. The abstract base classes also include the task-based async methods, which are missing from the interfaces.
using (DbConnection con = new SqlConnection("..."))
using (DbCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT 42 As TheAnswer";
await con.OpenAsync();
int result = (int)(await cmd.ExecuteScalarAsync());
}
Also, given the huge difference in the syntax used to access different databases / providers, you're unlikely to be able to reuse your database code anyway.
If your data access code is scattered around your application, even if you've used the interfaces or base classes, allowing the user to switch databases by editing a file would potentially be a nightmare. They would need to be able to change the CommandText and CommandType of every query, and define a map from your internal parameter names to the query parameters - possibly including duplicate mappings if the provider doesn't support named parameters.
If it's a requirement, it would probably be simpler to create a separate data access assembly for each supported provider, and use some form of DI to let the user swap providers as required. At which point, you do need an interface for the data access classes.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: Unfortunately, not the best example. Best example I could come up with based on practical use. It is a pattern that is easily recognized because many people used it in one form or another, and where you have an easy to explain benefit that is easily achieved.
Richard Deeming wrote: Also, given the huge difference in the syntax used to access different databases / providers, you're unlikely to be able to reuse your database code anyway. Yes. Next to their specialized dialects most databases also adhere to some form of a standard, with mine being SQL92.
I am not saying that you can make a complex application database-independant by swapping out some type-declarations, I'm claiming it is one of the things you can achieve if you are aware of their existence.
Another simple example would be to program against an interface and couple it with a class lateron. Something like "ISomeFancyEngine engine = new ISomeFancyEngine()". Not the best way to highlight anything an interface can do, but an example that shows a direct benefit one might have.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Actually, I am working on a Windows application and I want to add inkPicture to capture users signatures to the database. The signature column data type is varbinary. The problem is that the record is added to the database but it shows it as null only.
This is what I have done so far:
string con = "Data Source=SAIUNIFLOW;Initial Catalog=documentfollowup;Integrated Security=True";
byte[] saveInk = (byte[])axInkPicture1.Ink.Save(InkPersistenceFormat.IPF_GIF, InkPersistenceCompressionMode.IPCM_Default);
cmdDatabase = new SqlCommand();
cmdDatabase.Connection = conDatabase;
cmdDatabase.CommandText= "insert into manage (Signature)" + "values('" + axInkPicture1 + "'); ";
cmdDatabase.Parameters.AddWithValue("@Signature", saveInk);
Iam using tablet for getting the signatures but when I click the insert button, I receive that error:
Cannot insert the null value into column Signature, table doesn't allow nulls.
Hopefully to help me to solve this error.
|
|
|
|
|
|
|
Thank you for your reply. The same error. It is showing saveInk as null
|
|
|
|
|
I received the following error in
cmdDatabase.Parameters.AddWithValue("@Signature", saveInk);
which is
object reference is not set to the instance of object
|
|
|
|
|
So debug your code and find out which object is null .
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Where did you assign a value to saveInk? How does your current code look?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi, is it possible to convert a char array to a nullable char array?
string myString;
char?[] charArray = (char?[])(myString.ToCharArray());
modified 17-Oct-16 9:26am.
|
|
|
|
|
Not directly. Each element has to be cast to a char?. Probably use Linq
char?[] charArray = myString.Cast<char?>().ToArray()
Cheers,
Mick
------------------------------------------------
It doesn't matter how often or hard you fall on your arse, eventually you'll roll over and land on your feet.
|
|
|
|
|
No, Char is just a single letter or number. Char[] is a list of Chars. You can loop the list and concatenate a string or if the list have a fixed size declare a Char for each element and fill when you loop the list.
|
|
|
|
|
I have a form with three controls: updateprogress, AsyncFileUpload and button; my problem is de next one:
I have two stages:
--- Stage 1 using AsyncFileUpload
1.- When press the button (with trigger PostBackTrigger), UpdateProgress not appear but AsyncFileUpload works fine.
2.- When press then button (with trigger AsyncPostBackTrigger), Udateprogress appear but not disappear any more.
--- Stage 2 without AsyncFileUpload (removing control AsyncFileUpload)
1.- When press the button (with trigger PostBackTrigger), UpdateProgress not appear.
2.- When press then button (with trigger AsyncPostBackTrigger), Udateprogress appear and disappear.
My problem is that i need using AsyncFileUpload with updateprogress but no works properly.
Any body know what´s my problem?
if you wish, i can send you my project by email.
Greetings and sorry by my English.
|
|
|
|
|
It sounds to me like you may not be marshalling the calls to your controls back on to the UI thread. Whenever you make a call to a control, or set a property, you need to use the "InvokeRequired ...Invoke " pattern. Take a look here[^] - it explains it all. The pattern I speak of is about 1/3 of the way down the page.
Cheers,
Mick
------------------------------------------------
It doesn't matter how often or hard you fall on your arse, eventually you'll roll over and land on your feet.
|
|
|
|
|
That's not really relevant in an ASP.NET application.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I am trying to print a questionnaire which has 6 check-boxes. I am following a tutorial but this tutorial does not have check-boxes. Below prints except for the check-box. The text in the checkbox prints but prints if checked or not. I need some kind of statement to print if checked but cant find any examples of doing so.
private void metroButton3_Click(object sender, EventArgs e)
{
DSprintPreviewDialog.Document = DSprintDocument;
DSprintPreviewDialog.ShowDialog();
}
private void DSprintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Bitmap bmp = Properties.Resources.dslogo;
Image newImage = bmp;
e.Graphics.DrawString("Customer Name: " + metroTextBox2.Text, new Font("Arial", 16, FontStyle.Regular), Brushes.Black, new Point(25, 180));
e.Graphics.DrawString("Date: " + DateTime.Now, new Font("Arial", 12), Brushes.Black, new Point(25, 100));
e.Graphics.DrawString("Computer Make: " + metroMakeBox28.Text, new Font("Arial", 14, FontStyle.Regular), Brushes.Black, new Point(25, 250));
e.Graphics.DrawString("Customer Items: " + metroCheckBox1.Text, new Font("Arial", 14, FontStyle.Regular), Brushes.Black, new Point(25, 320));
I've changed the following but it prints with a True or False
e.Graphics.DrawString("Customer Items: " + metroCheckBox1.Checked + metroCheckBox1.Text, new Font("Arial", 14, FontStyle.Regular), Brushes.Black, new Point(25, 320));
|
|
|
|
|
If you are asking what I think you are asking, this[^] is how you write an if statement in C#.
|
|
|
|
|